2013-11-04 46 views
2

我有一个文件夹,其中包含不同的子文件夹。我必须遍历所有文件,并检查John和Jose的出现情况,并分别替换为Mikel和Mourinho。Python文件未找到错误

这是我用Python编写的脚本。它工作正常,但当我遇到一个.gif文件时,它给我一个错误,它不会进一步迭代。

你能告诉我为什么吗?

的错误是

Traceback (most recent call last): 
    File "C:\Users\sid\Desktop\script.py", line 33, in <module> 
    os.chmod(path ,stat.S_IWRITE) 
FileNotFoundError: [WinError 2] The system cannot find the file specified:'C:\Users\sid\Desktop\test\\images/ds_dataobject.gif.bak' 

我的代码:

import os,stat 
import fileinput 
import sys 

rootdir ='C:\Users\spemmara\Desktop\test' 
searchTerms={"John":"Mikel", "Jose":"Mourinho"} 

def replaceAll(file,searchExp,replaceExp): 
    for line in fileinput.input(file, inplace=1): 
     if searchExp in line: 
      line = line.replace(searchExp,replaceExp) 
     sys.stdout.write(line) 

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
     path=subdir+'/'+file 
     print(path) 
     os.chmod(path ,stat.S_IWRITE) 
     for key,value in searchTerms.items(): 
      replaceAll(path,key,value) 
     os.chmod(path,stat.S_IREAD) 

回答

4

使用原始字符串或双blackslashes \\

没有\\或原始字符串'\t'转换为标签空间:

>>> print 'C:\Users\spemmara\Desktop\test' 
C:\Users\spemmara\Desktop est 

随着原始字符串:

>>> print r'C:\Users\spemmara\Desktop\test' 
C:\Users\spemmara\Desktop\test 

双blackslashes:

>>> print 'C:\\Users\\spemmara\\Desktop\\test' 
C:\Users\spemmara\Desktop\test 

更新:

'C:\Users\sid\Desktop\test\images/ds_dataobject.gif.bak'

望着你想在混合\/错误单路径,更好使用os.path.join

path = os.path.join(subdir, file) 
+0

的代码工作。它将取代与穆里尼奥一起使用Jose的文件,但是当存在一个.gif文件时,它会给出错误信息。那么它是原始字符串 – Wolf

+0

的问题,我已经尝试过与其他文件夹也说,C:\ Users \ spemmara \ Desktop \ Source。即使这个文件夹的代码正在工作。这是取代,如果这是你提到的问题,那么它不应该给错误的权利 – Wolf

+0

gifs是另一个问题与原始字符串无关 – aIKid

0

除了hcwhsa的答案,你也可以工作,用硬件的方式,通过使用双反斜线:

rootdir = 'C:\\Users\\spemmara\\Desktop\\test' 

昨天我失去了我的水晶球,但我想另一件事是给你带来问题,是因为当你的程序创建一个gif文件时,你正在试图向它写文本。

如果你不想这样做,只是一个条件测试:

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
     path=subdir+'/'+file 
     print(path) 
     os.chmod(path ,stat.S_IWRITE) 
     if '.gif' not in path: 
      for key,value in searchTerms.items(): 
       replaceAll(path,key,value) 
     os.chmod(path,stat.S_IREAD)