简体   繁体   中英

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

I prefer to use glob when reading several files in a directory

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:

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 ). To get the .txt files from all sub-directories, use the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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