Python3 _io.TextIOWrapper 用记事本打开文件时出错

Python3 _io.TextIOWrapper error when opening a file with notepad

我的微型地址簿项目中的一个问题被困了几天。我有一个函数,可以将 SQLite3 Db 中的所有记录写入文件,以便通过 OS 模块打开,但是一旦我尝试打开文件,Python 就会出现以下错误:

Error while opening tempfile. Error:startfile: filepath should be string, bytes or os.PathLike, not _io.TextIOWrapper

这是我必须在文件上写入记录并打开它的代码:

        source_file_name = open("C:\workdir\temp.txt","w")
        #Fetching results from database and storing in result variable
        self.cur.execute("SELECT id, first_name, last_name, address1, address2, zipcode, city, country, nation, phone1, phone2, email FROM contacts")
        result = self.cur.fetchall()

        #Writing results into tempfile
        source_file_name.write("Stampa Elenco Contatti\n")
        for element in result:
            source_file_name.write(str(element[0]) + "|" + str(element[1]) + "|" + str(element[2]) + "|" + str(element[3]) + "|" + str(element[4]) + "|" + str(element[5]) + "|" + \
                str(element[6]) + "|" + str(element[7]) + "|" + str(element[8]) + "|" + str(element[9]) + "|" + str(element[10]) + "|" + str(element[11]) + "\n")

        #TODO: Before exiting printing function you MUST:
        # 1. filename.close()
        # 2. exit to main() function
        source_file_name.close()
        try:
            os.startfile(source_file_name,"open")
        except Exception as generic_error:
            print("Error while opening tempfile. Error:" + str(generic_error))
        finally:
            main()

坦率地说,我不明白这个错误是什么意思,在我以前的代码片段中,我总是可以毫无问题地处理文本文件,但我意识到这次不同,因为我是从数据库中选择我的流​​。任何想法如何解决它? 提前致谢,对不起我的英语...

你的问题最终源于糟糕的变量命名。这里

source_file_name = open("C:\workdir\temp.txt","w")

source_file_name不包含源文件名。它包含源文件 本身 (即文件句柄)。您不能将其提供给 os.startfile(),它需要一个文件路径(正如错误也指出的那样)。

你的意思是

source_file_name = "C:\workdir\temp.txt"
source_file = open(source_file_name,"w")

但实际上,在 Python 中使用 with 块要好得多,因为这将为您处理关闭文件。

最好使用 CSV writer 而不是手动创建 CSV,并且强烈建议明确设置文件编码。

import csv

# ...

source_file_name = "C:\workdir\temp.txt"

with open(source_file_name, "w", encoding="utf8", newline="") as source_file:
    writer = csv.writer(source_file, delimiter='|')

    source_file.write("Stampa Elenco Contatti\n")

    for record in self.cur.fetchall():
        writer.writerow(record)

    # alternative to the above for loop on one line
    # writer.writerows(self.cur.fetchall())