python-3.x - 使用记事本打开文件时出现 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()
坦率地说,我不明白这个错误是什么意思,在我以前的代码片段中,我总是毫无问题地处理文本文件,但我意识到这次不同,因为我是从数据库中选择我的流。任何想法如何解决它?提前谢谢,对不起我的英语......
解决方案
您的问题最终源于糟糕的变量命名。这里
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())
推荐阅读
- typescript - 第二个参数类型取决于打字稿中的第一个参数
- reactjs - 如何防止一个组件中的 css 影响 React 中另一个组件中的 css?
- c++ - 如何创建 addEdge 函数?
- oauth - GitLab 中允许用户仅使用 oauth 令牌访问公共存储库的范围是什么?
- typescript - 将打字稿字符串转换为代码但不断获取 _os.platform 未定义
- r - R中的Uniroot上限和下限
- redis - Redis 集群分布式密钥槽
- c - 用逗号返回语句
- c++ - 数值函数返回值是否需要显式 static_cast?
- django - Kuberntes:仅 Django + Gunicorn / 路径工作