简体   繁体   English

如何从数组中打开多个文本文件?

[英]How to open multiple text files from an array?

I want to open and read several text files.我想打开并阅读几个文本文件。 The plan is to find a string in the text files and print the whole line from the string.计划是在文本文件中找到一个字符串并从字符串中打印整行。 The thing is, I can´t open the paths from the array.问题是,我无法从数组中打开路径。 I hope it is unterstandable what I want to try.我希望我想尝试的东西是无法理解的。

import os
from os import listdir
from os.path import join
from config import cred

path = (r"E:\Utorrent\Leaked_txt")
for filename in os.listdir(path):
    list = [os.path.join(path, filename)]
    print(list)

for i in range(len(list)-1):
    with open(str(list[i], "r")) as f:
        for line in f:
            if cred in line:
                print(line)

Thanks :D感谢:D

I prefer to use glob when reading several files in a directory我更喜欢在读取目录中的多个文件时使用 glob

import glob

files = glob.glob(r"E:\Utorrent\Leaked_txt\*.txt") # read all txt files in folder

for file in files: # iterate over files
    with open(file, 'r') as f: # read file
        for line in f.read(): # iterate over lines in each file
            if cred in line: # if some string is in line
                print(line) # print the line

With os , you can do something like this:使用os ,您可以执行以下操作:

import os
from config import cred 

path = "E:/Utorrent/Leaked_txt"
files = [os.path.join(path, file) for file in os.listdir(path) if file.endswith(".txt")]

for file in files:
    with open(file, "r") as f:
        for line in f.readlines():
            if cred in line:
                print(line)

Edit编辑

os.listdir only includes files from the parent directory (specified by path ). os.listdir仅包含来自父目录(由path指定)的文件。 To get the .txt files from all sub-directories, use the following:要从所有子目录中获取 .txt 文件,请使用以下命令:

files = list()
for root, _, f in os.walk(path):
    files += [os.path.join(root, file) for file in f if file.endswith(".txt")]

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

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