簡體   English   中英

如何從數組中打開多個文本文件?

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

我想打開並閱讀幾個文本文件。 計划是在文本文件中找到一個字符串並從字符串中打印整行。 問題是,我無法從數組中打開路徑。 我希望我想嘗試的東西是無法理解的。

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)

感謝:D

我更喜歡在讀取目錄中的多個文件時使用 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

使用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)

編輯

os.listdir僅包含來自父目錄(由path指定)的文件。 要從所有子目錄中獲取 .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