Python:列出目录及其子目录中的所有文件名,然后将结果打印到txt文件中 [英] Python: List all the file names in a directory and its subdirectories and then print the results in a txt file

查看:58
本文介绍了Python:列出目录及其子目录中的所有文件名,然后将结果打印到txt文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题如下.我想列出我的目录及其子目录中的所有文件名,并将该输出打印在 txt 文件中.现在这是我到目前为止的代码:

My problem is as follows. I want to list all the file names in my directory and its subdirectories and have that output printed in a txt file. Now this is the code I have so far:

import os

for path, subdirs, files in os.walk('\Users\user\Desktop\Test_Py'):
   for filename in files:
     f = os.path.join(path, filename)
     a = open("output.txt", "w")
     a.write(str(f)) 

这会列出文件夹中文件的名称(有 6 个),但每个新文件都会覆盖旧文件,因此在任何给定时间 output.txt 文件中都只有一个文件名.如何更改此代码以将所有文件名写入 output.txt 文件中?

This lists the names of the files in the folders (there are 6) but each new file overwrites the old so there is only one file name in the output.txt file at any given time. How do I change this code so that it writes all of the file names in the output.txt file?

推荐答案

不要在 for 循环中打开文件.在 for 循环之前打开它

don't open a file in your for loop. open it before your for loop

喜欢这个

import os

a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
   for filename in files:
     f = os.path.join(path, filename)
     a.write(str(f) + os.linesep) 

或者使用上下文管理器(这是更好的做法):

Or using a context manager (which is better practice):

import os

with open("output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
       for filename in files:
         f = os.path.join(path, filename)
         a.write(str(f) + os.linesep) 

这篇关于Python:列出目录及其子目录中的所有文件名,然后将结果打印到txt文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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