简体   繁体   中英

Python File not found error

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)

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM