每次我的python文件运行时如何创建文本文件?

时间:2016-11-23 13:22:24

标签: python file text text-files

我想创建一个程序,将数据保存到文本文件中,每次程序运行时都应该创建一个文本文件。 有没有办法做到这一点。

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

# this will create a file in the current directory 
# from where your are executing your python script
f = open('somefile.txt', 'w')
# write some data into your file
f.write('some string\n')
# then close your file
f.close()

这是最简单的脚本,当您运行它时,它将创建一个文件并在其中写入some string。但这是处理文件的非常原始的方式。

在处理文件时,还有另一种方法被视为最佳做法。它是使用with上下文管理器,如下所示:

with open('somefile.txt', 'w') as f:
    f.write('your stuff')

正如您所看到的,它更短,更干净且缺少closing the file部分,因为with上下文管理器会为您执行此操作,因此您无需为关闭文件而烦恼。