使用python中print语句中的“file=file_name”写入文件

2024-05-29 01:43:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在第4章的headfirstpython一书中,他们使用了语法

print(list_name, file= output_file_name)

{cd1>对他们来说语法很好。python版本是相同的,即3。在

代码: 导入操作系统

人=[] 其他=[]

尝试: 数据=打开('草图.txt')

^{pr2}$

IOError除外: print('缺少数据文件!')在

尝试: man_file=打开('man_txt数据','w') other_file=open('其他_数据.txt','w')

print(man, file=man_file)
print(other, file=other_file)

IOError除外: print('文件错误')

最后: 男人_文件.close() 其他_文件.close()


Tags: 文件数据nametxtcloseoutput语法list
1条回答
网友
1楼 · 发布于 2024-05-29 01:43:09

根据打印功能的帮助指示

file: a file-like object (stream); defaults to the current sys.stdout.

所以输入不应该是文件名,而是一个类似文件的对象。如果你想写(比如)一个文本文件,你需要先打开它来写,然后使用文件句柄。在

f = open("output.txt",'w')
print(list_name, file=f)

相关问题 更多 >

    热门问题