[英]how to open multiple file from single file which is having list of files in python and how to do processing on them?
i am having single file called bar.txt which is having list of files as follows,我有一个名为 bar.txt 的文件,它的文件列表如下,
bar.txt - bar.txt -
1.txt 1.txt
2.txt 2.txt
3.txt 3.txt
each file inside bar.txt having some similar contents. bar.txt 中的每个文件都有一些相似的内容。
1.txt - 1.txt -
spec = sadasdsad规格=sadasdsad
2.txt - 2.txt -
spec = dddddd规格 = dddddd
3.txt - 3.txt -
spec = ppppppppp规格 = ppppppppp
how can i open all files inside bar.txt and extract the data from all file and store in other file called foo.txt?如何打开 bar.txt 中的所有文件并从所有文件中提取数据并存储在另一个名为 foo.txt 的文件中?
in foo.txt i want extracted data mentioned below,在 foo.txt 我想要提取下面提到的数据,
foo.txt - foo.txt -
spec = sadasdsad规格=sadasdsad
spec = dddddd规格 = dddddd
spec = ppppppppp规格 = 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()
I'd do this:我会这样做:
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()
You're code is almost correct.你的代码几乎是正确的。 I guess you messed everything up by using f
variable for almost everything.我猜您几乎对所有内容都使用了f
变量,从而搞砸了一切。 So you assign multiple different things to one f variable.因此,您将多个不同的东西分配给一个 f 变量。 First its single line on outfile, then it's the same line striped, then it's another opened file, and finally you try to use the same f variable outside of it's scope (outside for loop).首先它在 outfile 上的单行,然后是同一行条纹,然后是另一个打开的文件,最后你尝试在它的 scope 之外使用相同的 f 变量(在 for 循环之外)。 Try using different variables for all theses beings.尝试对所有这些存在使用不同的变量。
Also make sure you have correct indents (eg for
loop indent is incorrect in your example), and not that regex findall
works on string, not file-like object, so second argument of findall
should be contentfile.read()
.还要确保您有正确的缩进(例如for
loop indent 在您的示例中不正确),而不是正则表达式findall
适用于字符串,而不是类似文件的 object,因此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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.