Python File not found error

自作多情 提交于 2019-12-11 02:52:31

问题


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.

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.

Can you please tell me why?

The error is

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'

My code:

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)

回答1:


Use a raw string or Double blackslashes \\:

Without \\ or raw string '\t' is converted to a tab space:

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

With raw string:

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

Double blackslashes:

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

Update:

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

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)



回答2:


In addition to hcwhsa's answer, you can also work it the hard way, by using double backslashes:

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

I lost my crystal ball yesterday, but i guess another thing that is giving you problems, is because when your program founds a gif file, you're trying to write text to it.

If you don't want to do it, just test it with a condition:

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)


来源:https://stackoverflow.com/questions/19767179/python-file-not-found-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!