首页 > 解决方案 > 使用记事本打开文件时出现 Python3 _io.TextIOWrapper 错误

问题描述

我被困在我的微型通讯录项目中的一个问题上几天。我有一个函数可以将 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()

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

标签: python-3.xpython-3.6

解决方案


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

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 编写器而不是手动创建 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())

推荐阅读