0

Possible Duplicate:
IOError when trying to open existing files

I'm having problems opening a file with open() in python 3.3, any idea why?
I'm trying

import os

filelist = [ f for f in os.listdir( os.curdir )]
singleFile = filelist[a]
hppfile = open(singleFile, 'r')

And I get

FileNotFoundError: [Errno 2] No such file or directory: '-file that is actually inside the directory-'

Ideas?
On Windows, I just started this to learn this to write few quick scripts

3
  • 1
    os.listdir() returns a filename, not a full path. Commented Jan 26, 2013 at 19:27
  • os.listdir() already returns a list, and the default argument is already os.curdir btw. But I cannot reproduce this problem with files in the current directory, so I suspect your code sample does not match your real code. Commented Jan 26, 2013 at 19:31
  • @MartijnPieters Full code - it's only few lines, so I'm not sure what could be wrong with it, really Commented Jan 26, 2013 at 19:34

1 Answer 1

1

If you read the documentation for listdir you will see that it returns filenames and not full path.

You will need something like

current_dir_path = os.getcwd()
open(os.path.join(curren_dir_path, file), 'r')
Sign up to request clarification or add additional context in comments.

4 Comments

I already stated that in a comment, but the OP is listing the current directory.
So in python you need whole path to open a file? I thought it could be a relative path like in C++ is in default
@P.K.: relative paths should work just fine.
Oh well, that worked, no errors, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.