简体   繁体   English

Python 3.6:循环遍历 os.listdir() 中的文件并将其中一些写入文本文档

[英]Python 3.6: Looping through files in os.listdir() and writing some of them to a text document

I'm trying to loop through some files and write the file names of the .txt ones to another .txt我正在尝试遍历一些文件并将 .txt 的文件名写入另一个 .txt

the piece of code stops after finding and writing the name of one file.这段代码在找到并写入一个文件的名称后停止。

how would I get it to write the names of the rest?我如何让它写出其余的名字?

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == '.txt':
        with open('file_test.txt', 'r+') as ft:
            ft.write(file_name)

Opening the file only once before the loop would be much more efficient.在循环之前只打开一次文件会更有效率。 And better to pass your path to os.listdir() than to change directory:最好将您的路径传递给os.listdir()不是更改目录:

import os

with open('file_test.txt', 'w') as ft:
    for f in os.listdir('/users/user/desktop/directory/sub_directory'):
        file_name, file_ext = os.path.splitext(f)
        if file_ext == '.txt':
            ft.write(file_name)

And finally, if you want all ".txt" file in a directory, glob.glob is your friend ...最后,如果你想要一个目录中的所有“.txt”文件, glob.glob是你的朋友......

You need to open the destination file in "append" mode您需要以“追加”模式打开目标文件

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == '.txt':
        with open('file_test.txt', 'a+') as ft:
            ft.write(file_name)

Just put "a+" as second argument of your open function (where "a" stays for "append" and "+" for "create if not exists").只需将“a+”作为打开函数的第二个参数(其中“a”表示“追加”,“+”表示“如果不存在则创建”)。 I suggest you to add a separator (like a "\\n") in your write function to have more readable results我建议您在 write 函数中添加一个分隔符(如“\\n”)以获得更具可读性的结果

If you are on windows then you have to use \\\\\\ while specifying path of the directory.如果您在 Windows 上,则必须在指定目录路径时使用\\\\\\ and write to file in append mode.并以追加模式写入文件。看图

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

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