如何从 python 中具有文件列表的单个文件打开多个文件以及如何对它们进行处理?

how to open multiple file from single file which is having list of files in python and how to do processing on them?

我有一个名为 bar.txt 的文件,其中包含如下文件列表,

bar.txt-

1.txt

2.txt

3.txt

bar.txt 中的每个文件都有一些相似的内容。

1.txt-

spec = sadasdsad

2.txt -

规格=dddddd

3.txt-

规格 = ppppppppp

如何打开 bar.txt 中的所有文件并从所有文件中提取数据并存储在另一个名为 foo.txt 的文件中?

在foo.txt中我想要下面提到的提取数据,

foo.txt-

spec = sadasdsad

规格=dddddd

规格 = ppppppppp

 outfile = open('bar.txt', "rw")
 outfile_1 = open('foo.txt', "w")
     for f in outfile:
        f=f.rstrip()
        lines = open(f,'rw')
        lines = re.findall(".*SPEC.*\n",lines)
        outfile_1.write(lines)
 outfile.close()

我会这样做:

infile = open('bar.txt', "r")
outfile = open('foo.txt', "w")
line = infile.readline()

while line:
    f = line.rstrip()
    contents_file = open(f,'rw')
    contents = contents_file.read()
    outfile.write(contents)
    f = infile.readline()
 
outfile.close()

你的代码几乎是正确的。我猜你对几乎所有东西都使用 f 变量把一切都搞砸了。因此,您将多个不同的东西分配给一个 f 变量。首先是它在 outfile 上的单行,然后是同一行条纹,然后是另一个打开的文件,最后你尝试在它的范围之外(for 循环之外)使用相同的 f 变量。尝试为所有这些众生使用不同的变量。

还要确保你有正确的缩进(例如 for 循环缩进在你的例子中是不正确的),而不是正则表达式 findall 适用于字符串,而不是类文件对象,所以第二个参数findall 应该是 contentfile.read().

infile = open('bar.txt', "r")
outfile = open('foo.txt', "w")
for f in infile:
    name=f.rstrip()
    contentfile = open(name,'rw')
    #all_matches= re.findall(<define your real pattern here>,contentfile.read())
    result = 0 #do something with your all_matches
    outfile.write(result)
    contentfile.close()
outfile.close()
infile.close()