Python代码:将生成的文件保存到指定目录(D盘test目录)

如果您想将生成的txt文件放在D盘的'test'目录下,并在没有该目录时创建它,请使用以下修改后的代码:

from common.database import connect_database, close_database
import os

def create_txt_file(content):
    directory = 'D:/test'
    if not os.path.exists(directory):
        os.makedirs(directory)
    file_path = os.path.join(directory, content + '.txt')
    with open(file_path, 'w') as file:
        file.write(content)

def process_data(result):
    if os.path.exists('current_index.txt'):
        with open('current_index.txt', 'r') as file:
            current_index = int(file.read())
    else:
        current_index = 0

    while current_index < len(result):
        value = result[current_index][0]  # 获取结果元组的第一个元素,即title的值
        create_txt_file(value)
        current_index += 1

    with open('current_index.txt', 'w') as file:
        file.write(str(current_index))

    return current_index

conn, cursor = connect_database(host='', port=8066, user='', password='', database='', charset='')
sql = 'SELECT title FROM t_read_recite_resources'
cursor.execute(sql)
result = cursor.fetchall()

process_data(result)

close_database(conn, cursor)

在上述代码中,我添加了一个create_txt_file()函数,它现在会将txt文件保存在D盘的'test'目录下。如果该目录不存在,代码会先创建这个目录。

请注意,这段代码仅适用于Windows系统中的D盘。如果您使用的是其他操作系统或希望将文件保存到不同的目录,请相应地修改directory变量的值。

Python代码:将生成的文件保存到指定目录(D盘test目录)

原文地址: https://www.cveoy.top/t/topic/bNPh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录