在 for 循环中写入文件 [英] Writing to a file in a for loop

查看:121
本文介绍了在 for 循环中写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

text_file = open("new.txt", "r")

lines = text_file.readlines()

for line in lines:
        var1, var2 = line.split(",");
        myfile = open('xyz.txt', 'w')
        myfile.writelines(var1)
        myfile.close()
text_file.close()

我在 new.txt 中有 10 行文本,例如 Adam:8154乔治:5234 等等.现在我想要一个仅包含名称的文本文件.xyz.txt 必须包含 Adam George 等.现在上面的代码只给我留下了第 10 个名字.

I have 10 lines of text in new.txt like Adam:8154 George:5234 and so on. Now i want a text file which contains only the names. xyz.txt must contain Adam George and so on. Now the above code leaves me with the 10th name only.

如何在一个文本文件中包含所有 10 个名称.

How to have all the 10 names in a single text file.

推荐答案

那是因为你在 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

这篇关于在 for 循环中写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆