![](/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.