423,682 Members | 1,622 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,682 IT Pros & Developers. It's quick & easy.

No such file or directory:

P: 18
Ok i think it is the way i am telling the function what the path is. im guessing this only doesnt work because im on a windows machine (on python 2.5)

Expand|Select|Wrap|Line Numbers
  1. f = open('files\test.txt', 'r')
  2. for line in f:
  3.     print line
ive tried changing the string in all obvious ways

Expand|Select|Wrap|Line Numbers
  1. 'files\\test.txt'
  2. r'files\test.txt'
  3. 'files/test.txt'
  4. 'c:\....\files\test.py'
  5. 'c:\\...\files\test.py' (for the c:\ bug i tried c:\\)
Ok what am i missing here? ive been coding for years and this has stumped me. Google doesnt even have an answer. do people just not open files out of there directories in windows?
Jan 19 '10 #1
Share this Question
Share on Google+
4 Replies

Expert Mod 2.5K+
P: 2,851
Look what happens when a string with a backslash character is evaluated:
Expand|Select|Wrap|Line Numbers
  1. >>> print 'abcdef\thrt'
  2. abcdef    hrt
  3. >>> print r'abcdef\thrt'
  4. abcdef\thrt
  5. >>> 
Characters "\t" are evaluated as a tab character. Escape the backslash characters for a path as in:

or use the forward slash as in:

or use a raw string as in:

If the file is in your current working directory (os.getcwd()), you can omit the full path as in:

To read a file in the directory just above the CWD:

To read a file in a directory just below the CWD:
Jan 20 '10 #2

P: 18
thanks for the reply, turns out i miss typed the file when making it. to text.txt. but i got it working now thanks, one question though. if the file is dynamic eg
filename from sys.
Expand|Select|Wrap|Line Numbers
  1. f=open('files/'.filename,'r')
will this work for any value of filename, where filename is just a file (not a path) and the file exists.
Jan 20 '10 #3

Expert Mod 2.5K+
P: 2,851

Look at the glob module. Usage:
Expand|Select|Wrap|Line Numbers
  1. glob.glob(pathname) or glob.glob1(dirname, pattern)
From help(glob):
Returns a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch.

You may be referring to a file name stored in a variable. You can use string formatting. Example:
Expand|Select|Wrap|Line Numbers
  1. var = "filenameXYX.txt"
  2. open("dir1/dir2/%s" % (var))
Jan 20 '10 #4

P: 18
Yup, that's all clear now. Thanks a lot, fast and helpful forums here.
Jan 20 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.