简体   繁体   English

如何从目录路径列表中打开文件?

[英]How do I open files from a list of directory paths?

I have a list of folders that I need to open and read a .log file. 我有一个打开和读取.log文件所需的文件夹列表。 At first, I did not have the list of folders, so I was scanning all the files in the directory. 起初,我没有文件夹列表,所以我正在扫描目录中的所有文件。 This will lead to redundancy for what I want to use this for. 这将导致我要用于此目的的冗余。

path = '/home/User/Test/'
files = []

# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.log' in file:
            files.append(os.path.join(r, file))

for f in files:
    log_file = open(f, 'r')

    lines = log_file.readlines()
    log_file.close()

Now, I have a list paths which look like ['/home/User/Test/folder_test/Process1/Task1/2019-07-31T10%3A30%3A00+00%3A00', ...., 'final_path'] 现在,我有一个看起来像['/home/User/Test/folder_test/Process1/Task1/2019-07-31T10%3A30%3A00+00%3A00', ...., 'final_path']的列表paths

How can I loop through the paths so it is opening the folder, at then extracting the .log file? 如何遍历路径,以便打开文件夹,然后解压缩.log文件?

NOTE: I am getting rid of path = '/home/User/Test/' as I have the list of specific directories. 注意:我摆脱了path = '/home/User/Test/'因为我有特定目录的列表。

I think you can utilize the glob library for this problem. 我认为您可以利用全局库解决此问题。 It allows you to pattern-match your paths. 它允许您对路径进行模式匹配。

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

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