0

I'm having trouble with opening files, python (2.7) tells me that there is no such file, but there is.

        csvData = None
        csvHeader = None
        os.chdir("../result/files/")
        for fileName in os.listdir("."):
            if fileName.endswith(".csv"):
                print fileName
                with open("../result/files/"+fileName, 'rb') as csvFile:
                    readerCsv = reader(csvFile, delimiter = ';')
                    csvHeader = readerCsv.next()
                    _unused = readerCsv.next()
                    self.data = list.append(list(readerCsv))

this code is suposed to read 5 csv files and store their content in data (except for the first line)

At first chdir tells me he found Stats20120903.csv then I ask the program to open said file but I get an error :

IOError: [Errno 2] No such file or directory: '../files/Stats20120903.csv'

why?

Thanks

0

3 Answers 3

1

os.chdir does not tell you what is in the directory, it changes the current working path. All relative file path you give are relative to the working dir.

You should either

  • remove the os.chdir("../result/files/") and call os.listdir("../result/files/") or
  • not add "../result/files/" to the filename you want to open.
Sign up to request clarification or add additional context in comments.

1 Comment

removing os.chdir("../result/files/") and replacing "." by "../result/files/" worked, thanks
1

Do

with open(fileName, 'rb') as csvFile:

instead of looking relative to the directory you've changed to.

Comments

0

You could try using os.path.abspath() to find out what actual path Python is trying to use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.