[英]Concat all the text files and their content contained in all the .zip files in a text file using Python
我正在嘗試編寫一個程序來讀取文件夾中的所有文件並將它們的所有內容輸出到一個文件中。 文件以 .gz 擴展名壓縮。 我設法讀取了一個文件,但不是它的所有內容,而不是其余的文件。 這是我的代碼:
import glob, gzip, re
import pickle
filed = open('Logs.txt', 'w')
logfilenames = glob.glob('*.gz')
logformat = re.compile(r'^\S+ \S+ \S+ \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+) .*" (\d+) (\d+) "([^"]*)" "[^"]*"')
with gzip.GzipFile(logfilenames[0],'r') as f:
for i in glob.glob('*.gz'):
txtline = f.readline()
parsedline = logformat.match(txtline)
print "time={t} size={s} url={u}".format(t=parsedline.group(1), s=parsedline.group(5), u=parsedline.group(3))
pickle.dump(["time={t} size={s} url={u}".format(t=parsedline.group(1), s=parsedline.group(5), u=parsedline.group(3))],filed)
filed.close()
試試這個(沒有觸及你的正則表達式):
import glob, gzip, re
import cPickle
logformat = re.compile(r'^\S+ \S+ \S+ \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+) .*" (\d+) (\d+) "([^"]*)" "[^"]*"')
with open('Logs.txt', 'w') as f_out:
for i in glob.glob('*.gz'):
with gzip.GzipFile(i,'r') as f_in:
for txtline in f_in:
parsedline = logformat.match(txtline)
if parsedline:
f_out.write("time={t} size={s} url={u}".format(t=parsedline.group(1), s=parsedline.group(5), u=parsedline.group(3)))
將其另存為 xD.sh
mkdir dir
mv $file dir
cd dir
tar -zxvf $file
for file in `ls -w 1 | grep -v ".gz"`; do
cat $file >> joint-file
done
mv joint-file ../
rm -rf dir
然后從 python 中使用它
import os
cmd = './xd.sh'
os.system(cmd)
=)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.