简体   繁体   English

在python中读取目录中的所有文件

[英]read all the files in a directory in python

我对 python 很陌生。我有一个目录,里面有 2 个子目录。每个子目录包含 100 个文本文件。我想读取两个子目录的每个文件的内容并将它们放在一个文本中文件的方式是每个文件内容都在新文件中的一行中。我如何在 pyhon 中实现这一点。谢谢

Since you don't have anything.. you could try starting from here.既然你什么都没有……你可以试着从这里开始。 You can use the glob module instead to load files from a single level of subdirectories, or use os.walk() to walk an arbitrary directory structure depending on your requirement,您可以使用 glob 模块从单个级别的子目录加载文件,或者使用 os.walk() 根据您的要求遍历任意目录结构,

To open say all text files in an arbitrary nesting of directories:要打开任意嵌套目录中的所有文本文件:

 import os
 import fnmatch

 for dirpath, dirs, files in os.walk('Test'):
    for filename in fnmatch.filter(files, '*.txt'):
        with open(os.path.join(dirpath, filename)):
            # deal with this file as next loop will present you with a new file. 
            #use the filename object to do whatever you want with that file

Since your new like you said.既然你说的新。 Watch out for the indentations.注意凹痕。 #Goodluck #祝你好运

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

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