【问题标题】:How to open multiple text files from an array?如何从数组中打开多个文本文件?
【发布时间】:2021-09-27 23:49:41
【问题描述】:

我想打开并阅读几个文本文件。计划是在文本文件中找到一个字符串并从字符串中打印整行。问题是,我无法打开阵列中的路径。 我希望我想尝试的东西是不可理解的。

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

【问题讨论】:

  • 当你说你不能从数组中打开路径时,你是什么意思?您遇到了什么错误?
  • 我没有收到错误,但它也没有打印任何内容,所以我可能搞砸了
  • 你不应该使用list作为变量名,因为它是一个Python关键字。
  • 该死的我应该更多地了解python。我的坏

标签: python arrays python-3.x arraylist text


【解决方案1】:

我更喜欢在读取目录中的多个文件时使用 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

【讨论】:

  • 到目前为止工作,但我现在收到此错误:发生异常:UnicodeDecodeError 'charmap' codec can't decode byte 0x9d in position 7656: character maps to
  • 如果您的所有文件都是UTF-8,那么您可以尝试添加编码:with open(file , 'r', encoding='utf8') as f:
  • 不,突然明白了:发生异常:UnicodeDecodeError 'utf-8' codec can't decode byte 0xfb in position 7685: invalid start byte
  • 您的文件是如何编码的,ASCII?您也可以尝试添加read()
  • 如果我打开它们有utf8,我该如何检查它们?
【解决方案2】:

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

【讨论】:

  • 感谢您的回复,我也收到了这个错误:'charmap' codec can't decode byte 0x9d in position 7656: character maps to
  • @t0xic - 这是一个完全不同的问题。见here。您可能需要一个 try/except 博客,在其中尝试使用多种编码读取文件。
  • 好的,知道了。剩下一个问题,我怎样才能删除“[]”,因为这些都是为每一行打印的?
  • @t0xic - 已编辑 :)
  • 非常感谢:D
猜你喜欢
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多