2024-04-18 18:11:33 发布
网友
我想创建一个程序,将数据保存到一个文本文件,它应该创建一个文本文件,每次我的程序运行。 有什么办法吗。你知道吗
您可以尝试以下方法:
# 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。但这是一种非常原始的处理文件的方法。你知道吗
some string
在处理文件时,还有另一种被视为最佳实践的方法。使用with上下文管理器如下:
with
with open('somefile.txt', 'w') as f: f.write('your stuff')
如您所见,它更短、更干净,并且缺少closing the file部分,因为with上下文管理器为您完成了这项工作,所以您不需要费心关闭文件。你知道吗
closing the file
您可以尝试以下方法:
这是最简单的脚本,当您运行它时,它将创建一个文件并在其中写入
some string
。但这是一种非常原始的处理文件的方法。你知道吗在处理文件时,还有另一种被视为最佳实践的方法。使用
with
上下文管理器如下:如您所见,它更短、更干净,并且缺少
closing the file
部分,因为with
上下文管理器为您完成了这项工作,所以您不需要费心关闭文件。你知道吗相关问题 更多 >
编程相关推荐