我正在尝试编写一个程序来读取文件夹中的所有文件,并将所有内容输出到一个文件中。这些文件使用.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()
答案 0 :(得分:3)
试试这个(没有触及你的正则表达式):
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)))
答案 1 :(得分:0)
将其保存为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)
=)