[Tutor] File not found error, but it is in the folder!

Dave Angel davea at davea.name
Wed Apr 10 18:22:29 CEST 2013


On 04/10/2013 10:44 AM, Woody 544 wrote:
> I have a script that worked before I moved it to another folder.  I
> cannot understand why I am getting a 'No such file or directory'
> error, when the file is in the folder.
>
> Any clues would be much appreciated.  Thanks!
>
> MJ
>
> Here is a copy and paste of the script up to the error, output/error
> and a check for the file:
>
> SCRIPT:
> import os, string, codecs
> os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')
>
> folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
> files = os.listdir(folder)
>
> #os.walk(folder)
>
> fy13q1dict = {'country' : 'countryname', 'title':'titlename',
> 'travel':'traveldata',
> 'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
> countryname = ()
> titlename = ()
>
> for i in files:
>      fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
>      fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
>      data = str(fp.read())
>      data = data.replace('\xa0',' ')
>      data = data.split()
>
> OUTPUT:
>>>>
>
> Traceback (most recent call last):
>    File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
> 22, in <module>
>      fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
>    File "C:\Python27\lib\codecs.py", line 881, in open
>      file = __builtin__.open(filename, mode, buffering)
> IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'
>
> CHECK FOR FILE IN FOLDER:
>>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')
> ['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir


As Mark points out, your problem is that you've used a different 
directory for os.chdir.

I'd like to point out that I'm heavily biased against ever changing 
"current working directory" in a non-trivial application.  The current 
directory is analogous to a global variable, and they should all be 
constant.  Now, if you want to change it once, at program entry, then 
it's like a constant that gets iniialized once.

But if you are going to use the chkdir, then all your code that deals 
with that directory should use relative paths.  If you'd done 
os.listdir(".") you'd have seen the problem.

My preference is to use absolute directories for every reference, in 
which case you'd use something like
     ...open(os.path.join(directory, i), ...

With of course a better name than 'i', which is traditionally an 
integer.  (since 1967, anyway)

-- 
DaveA


More information about the Tutor mailing list