python-3.x 从文件列表中写入新行

axr492tv  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(88)

我有一个清单,读取文件从一个给定的目录,然后打印出它到控制台,现在我想输出的文件列表到一个文件,我得到了工作除了它把它所有在一行,我怎么能添加一个新的行?我试过了,但没有什么用。我知道我用错了。这是我代码块。

for path in files:
            print(path)

            # Open the file for writing
            file = open('looking-for.txt', "w", encoding="utf-8")
            # grab the list for writing
            content = str(files)
            # write out the header to the file.
            file.write("----------------------------------\n")
            file.write("| Looking for files              |\n")
            file.write("----------------------------------\n")
            # write out the list to a file
            file.write(content)
            # close the file.
            file.close()

字符串
这是我试过的。

this dose not give me a new line.
file.write(string)
file.write("\n")

x

here is what I get.
drive:\path\to\file1, drive:\path\to\file2, drive:\path\to\file3
etc.
here is what I am trying to achieve.
drive:\path\to\file1
drive:\path\to\file2
drive:\path\to\file3
etc.

的字符串

6l7fqoea

6l7fqoea1#

首先,我认为你说你的产量是

drive:\path\to\file1, drive:\path\to\file2, drive:\path\to\file3

字符串
我认为你的实际产出是

['drive:\path\to\file1', 'drive:\path\to\file2', 'drive:\path\to\file3']


这正是列表的字符串格式,这就是你在这里构建的:

# grab the list for writing
content = str(files)


评论也是完全错误的。你不是在“抓取”列表,而是在将整个文件列表重新格式化为一种你根本不想要的格式。
此外,您在循环中重新执行此操作,对于每个路径,重写具有头文件和整个错误文件列表的整个输出。什么?显然不是。您希望只打开文件一次,只写入头文件一次,然后写入每个文件。
总而言之:

with open ('looking-for.txt', "w", encoding="utf-8") as file:
    file.write("----------------------------------\n")
    file.write("| Looking for files              |\n")
    file.write("----------------------------------\n")

    for path in files:
        file.write(path + '\n')

    # Alternatively write all files at once by formatting
    # the content the way we *actually* want it (joined by new-lines)
    # content = '\n'.join(files)
    # file.write(content)

相关问题