繁体   English   中英

如何使用 for 循环创建和编写文件?

[英]How do I create and write a file with for loop?

所以我有一个文本文件,里面有文字,我创建了一个 for 循环,它在文件中找到指定的字符串并打印出其中包含字符串的行。 但是现在我被卡住了,因为我想修改代码,这样我就可以编写一个包含它已经打印出来的新文件。

我试过四处寻找答案,但我似乎找不到任何解决方案,甚至找不到我想要做的事情。 我试着仔细查看了print function的参数和join方法。

file = open("datalist.txt", "r")
s = "hello"
file_export = open("newfile.txt", "w")

for lines in file:
    lines = lines.lower()
    index = lines.find(s)
    if index != -1:
        indexed = lines[index:]
        print(lines[index:], end='')

我需要的打印消息大致如下:

hello,
hello:
hello;

print不是您要查找的 function ,要写入需要使用file.write (或file.writeline )的文件,请查看输入和 output 文档

给出一个想法,你的代码应该是这样的:

file = open("datalist.txt", "r")
s = "hello"
file_export = open("newfile.txt", "w")

for lines in file:
    lines = lines.lower()
    index = lines.find(s)
    if index != -1:
        indexed = lines[index:]
        print(lines[index:], end='')
        file_export.write(lines[index:])

另外,请注意,完成后您应该关闭文件,因此在末尾添加以下内容:

file.close()
file_export.close()

或者,作为替代方案,使用自动关闭文件的上下文管理器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM