如何将设置列表打印到文本文件中的新行 python 3

How to print set list to new lines in text file python 3

基本上我想制作一个程序,它读取一个文本文件,对信息做一些事情,然后将不同的信息输出到一个文件中。

例如; input.txt 包含带有文本的不同行

然后我用这个转换成列表:

with open("input.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]

然后将列表输出到文本文件中,不像 ['string'、'string'] 而是换行。

有什么帮助吗???

$ cat input.txt
 HELLO
 WORLD

在 python 中,您可以使用 '\n' 向内容追加新行。

   with open("input.txt") as f:
        content = f.readlines()
        content = [x.strip() for x in content]
        content = '\n'.join(content)

读取文件并修改列表中的内容后。该列表可以写回文本文件,并为列表中的每个项目换行,如下所示:

with open('my_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

您可以像这样创建一个字符串:

elements_on_new_line = '\n'.join(my_list)

然后你在文件上写下变量'elements_on_new_line'

这样做

with open('my file.txt', 'w') as my_file:
    my_file.write(elements_on_new_line)