![](/img/trans.png)
[英]How to open multiple JSON file from folder and merge them in single JSON file in 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 -
规格=sadasdsad
2.txt -
规格 = dddddd
3.txt -
规格 = ppppppppp
如何打开 bar.txt 中的所有文件并从所有文件中提取数据并存储在另一个名为 foo.txt 的文件中?
在 foo.txt 我想要提取下面提到的数据,
foo.txt -
规格=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 上的单行,然后是同一行条纹,然后是另一个打开的文件,最后你尝试在它的 scope 之外使用相同的 f 变量(在 for 循环之外)。 尝试对所有这些存在使用不同的变量。
还要确保您有正确的缩进(例如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.