0

I'm new to python and the following piece of code is driving me crazy. It lists the files in a directory and for each file does some stuff. I get a IOError: [Errno2] No such file or directory: my_file_that_is_actually_there!

def loadFile(aFile):
  f_gz = gzip.open(aFile, 'rb')
  data = f_gz.read()
  #do some stuff...
  f_gz.close()
  return data

def main():
  inputFolder = '../myFolder/'
  for aFile in os.listdir(inputFolder):
    data = loadFile(aFile)
    #do some more stuff

The file exists and it's not corrupted. I do not understand how it's possible that python first finds the file when it checks the content of myFolder, and then it cannot find itanymore... This happens on the second iteration of my for loop only with any files.

NOTE: Why does this exception happen ONLY at the second iteration of the loop?? The first file in the folder is found and opened without any issues...

Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154
  • possible duplicate of [IOError when trying to open existing files](http://stackoverflow.com/questions/10802418/ioerror-when-trying-to-open-existing-files) – Martijn Pieters Nov 10 '12 at 21:59
  • Martijn, please check my edit (I added a note). This detail is not addressed in the question linked in your comment. – Marsellus Wallace Nov 10 '12 at 22:17
  • 2
    That can only happen if the local directory happens to have the *exact* same filename as found in `../myFolder/`. You are opening the wrong file. So if there is a `../myFolder/foo` there is *also* a `./foo`. – Martijn Pieters Nov 10 '12 at 22:18

1 Answers1

2

This is because open receives the local name (returned from os.listdir). It doesn't know that you mean that it should look in ../myFolder. So it receives a relative path and applies it to the current dir. To fix it, try:

data = loadFile(os.path.join(inputFolder, aFile))
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • Since `inputFolder` is a relative path, it is worth to note that it also depends on where the script is executed. This solution won't work when executed from the "wrong" directory. – Maehler Nov 10 '12 at 22:00
  • When run from a "wrong" directory, the script will probably fail at the `os.listdir` stage :) – Lev Levitsky Nov 10 '12 at 22:03
  • thanks, this works! But WHY does this problem arise only at the second iteration of the loop? Is there something that I have to know about python specifically? – Marsellus Wallace Nov 10 '12 at 22:05
  • @Gevorg It could be that the first iteration encounters a file name that happens to exist in both current directory and in `../myFolder/`. – user4815162342 Nov 10 '12 at 22:22