且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 for 循环中写入文件

更新时间:2022-03-19 03:06:22

那是因为你在 for 循环中打开、写入和关闭文件 10 次

That is because you are opening , writing and closing the file 10 times inside your for loop

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

你应该在 for 循环之外打开和关闭你的文件.

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

您还应该注意使用 write不使用 writelines.

writelines 将行列表写入您的文件.

writelines writes a list of lines to your file.

此外,您还应该查看这里使用 with 语句的人们发布的答案.这是在 Python 中进行文件读/写操作的优雅方式

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python