未找到 Python 文件错误

Wol*_*olf 2 python filenotfoundexception

我有一个文件夹,里面有不同的子文件夹。我必须遍历所有文件并检查 John 和 Jose 的出现并分别替换为 Mikel 和 Mourinho。

这是我用 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'
Run Code Online (Sandbox Code Playgroud)

我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 5

使用原始字符串或双黑斜线\\

没有\\或原始字符串'\t'被转换为制表符空间:

>>> print 'C:\Users\spemmara\Desktop\test'
C:\Users\spemmara\Desktop   est
Run Code Online (Sandbox Code Playgroud)

使用原始字符串:

>>> print r'C:\Users\spemmara\Desktop\test'
C:\Users\spemmara\Desktop\test
Run Code Online (Sandbox Code Playgroud)

双黑斜线:

>>> print 'C:\\Users\\spemmara\\Desktop\\test'
C:\Users\spemmara\Desktop\test
Run Code Online (Sandbox Code Playgroud)

更新:

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

看着你试图混合错误\,并/在一个单一的路径,更好地利用os.path.join

path = os.path.join(subdir, file)
Run Code Online (Sandbox Code Playgroud)