2016-11-16 90 views
1

我有比如这个代码部分:如何用python 35来复制和复制几个文件?

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() 

而且我想,而不是在外壳的打印效果,替换用新名称或在新目录中的文件复制应用到每一行的所有行(肯定不会犯错误)。 你有什么想法教我如何做到这一点?

回答

1

这真的很简单:您只需要定义输出目录并在该目录中打开一个新文件,以便每次打开读取的文件时写入。看看这个:

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) 
+0

好的答案,但'f'没有定义。 –

+0

谢谢,但... f是fpath中的文件?我应该这样做: 在fichiers中的fpath: fpath中的f: if os.path.isfile(f): –

+0

@ H.eyXD:你是对的!当我复制粘贴代码时,我应该更加小心:P – inspectorG4dget