简体   繁体   English

我想使用python遍历目录以获取文本文件并对其进行处理

[英]I want to use python to walk through directories to get to text files and processed them

I have many folders in a directory: 我在目录中有很多文件夹:

/home/me/Documents/coverage

/coverage contains 50 folders all beginning with H : /coverage包含50个以H开头的文件夹:

/home/me/Documents/coverage/H1   (etc)

In each H*** folder there is a text file which I need to extract data from. 每个H***文件夹中都有一个文本文件,我需要从中提取数据。

I have been trying to use glob and os.walk to use a script that is saved in /coverage to walk into each of these H folders, open the .txt file and process it, but I have had no luck at all. 我一直在尝试使用glob和os.walk来使用保存在/coverage的脚本进入每个H文件夹,打开.txt文件并进行处理,但是我一点都不走运。

Would this be a good starting point? 这将是一个很好的起点吗? (where path = /coverage ) (其中path = /coverage

for filename in glob.glob(os.path.join(path, "H*")):
    folder = open(glob.glob(H*))

And then try and open the .txt file? 然后尝试打开.txt文件吗?

Just gather all the txt files in one shot using glob wildcards. 只需使用全局通配符将所有txt文件收集在一起即可。 You can do it like that. 你可以那样做。

import glob
path = "/home/me/Documents/coverage/H*/*.txt"
for filename in glob.glob(path):
    fileStream = open(filename )

cheers 干杯

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

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