找不到Python档案错误 [英] Python File not found error
问题描述
我有一个包含不同子文件夹的文件夹.我必须遍历所有文件并检查John和Jose的出现,并分别替换为Mikel和Mourinho.
I have a folder with different subfolders in it. I have to iterate through all the files and check for the occurrences of John and Jose and replace with Mikel and Mourinho respectively.
这是我用Python编写的脚本.它工作正常,但是当我遇到.gif
文件时,这给了我一个错误,并且没有进行进一步的迭代.
This is the script I have written in Python. It is working fine but when I encounter a .gif
file it is giving me an error and it is not iterating further.
你能告诉我为什么吗?
错误是
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)
推荐答案
使用原始字符串或双斜杠\\
:
Use a raw string or Double blackslashes \\
:
没有\\
或原始字符串'\t'
都将转换为制表符空间:
Without \\
or raw string '\t'
is converted to a tab space:
>>> print 'C:\Users\spemmara\Desktop\test'
C:\Users\spemmara\Desktop est
带有原始字符串:
>>> print r'C:\Users\spemmara\Desktop\test'
C:\Users\spemmara\Desktop\test
双反斜杠:
>>> print 'C:\\Users\\spemmara\\Desktop\\test'
C:\Users\spemmara\Desktop\test
更新:
'C:\ Users \ sid \ Desktop \ test \ images/ds_dataobject.gif.bak'
'C:\Users\sid\Desktop\test\images/ds_dataobject.gif.bak'
查看您尝试在单个路径中混合\
和/
的错误,最好使用os.path.join
:
Looking at the error you're trying to mix \
and /
in a single path, better use os.path.join
:
path = os.path.join(subdir, file)
这篇关于找不到Python档案错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!