File 如何使用python 35修改和复制多个文件?
例如,我有以下代码部分:File 如何使用python 35修改和复制多个文件?,file,python-3.x,copy,File,Python 3.x,Copy,例如,我有以下代码部分: fichiers=glob.glob('/path/*.file') for f in fichiers: if os.path.isfile(f): fichier = open(f,'r') for l in fichier: m = regex.match(l) if m: print('%s/ EMO /%s'%(m.group(1),m.gr
fichiers=glob.glob('/path/*.file')
for f in fichiers:
if os.path.isfile(f):
fichier = open(f,'r')
for l in fichier:
m = regex.match(l)
if m:
print('%s/ EMO /%s'%(m.group(1),m.group(3)))
#here I want to write this modified line
else:
#write line non modified
fichier.close()
我希望,不是在shell中打印结果,而是将替换应用到每行的所有行,使用新名称或新目录复制文件(确保不会出错)。
你有什么想法可以教我怎么做吗?其实很简单:每次你打开一个你读过的文件时,你只需要定义你的输出目录并在该目录中打开一个新的文件进行写入。看看这个:
import glob
import os
outdirpath = "/path/to/output/directory"
for fpath in glob.glob('/path/*.file'):
if not os.path.isfile(fpath): continue
with open(fpath) as fichier, open(os.path.join(outdirpath, os.path.basename(fpath)), 'w') as outfile:
for line in fichier:
m = regex.match(line)
if m:
outfile.write('%s/ EMO /%s'%(m.group(1),m.group(3)))
else:
outfile.write(line)
回答得很好,但是没有定义
f
。谢谢,但是。。。f是fpath中的文件吗?我应该做什么:对于fichiers中的fpath:对于fpath中的f:if os.path.isfile(f):@H.eyXD:你说得对!复制粘贴代码时,我应该更加小心:P