No such file or directory:

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iamfletch
    New Member
    • Jan 2010
    • 18

    No such file or directory:

    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)

    Code:
    f = open('files\test.txt', 'r')
    for line in f:
    	print line
    ive tried changing the string in all obvious ways

    Code:
    'files\\test.txt'
    r'files\test.txt'
    'files/test.txt'
    'c:\....\files\test.py'
    '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?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Look what happens when a string with a backslash character is evaluated:
    Code:
    >>> print 'abcdef\thrt'
    abcdef	hrt
    >>> print r'abcdef\thrt'
    abcdef\thrt
    >>>
    Characters "\t" are evaluated as a tab character. Escape the backslash characters for a path as in:
    'D:\\SD\\plugin s\\Embed\\Defau lts\\EmbedPL.tx t'

    or use the forward slash as in:
    'D:/SD/plugins/Embed/Defaults/EmbedPL.txt'

    or use a raw string as in:
    r'D:\SD\plugins \Embed\Defaults \EmbedPL.txt'

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

    To read a file in the directory just above the CWD:
    open("..\\Embed PL.txt").read()

    To read a file in a directory just below the CWD:
    open("subdir_na me\\EmbedPL.txt ").read()

    Comment

    • iamfletch
      New Member
      • Jan 2010
      • 18

      #3
      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.
      Code:
      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.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        iamfletch:

        Look at the glob module. Usage:
        Code:
        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:
        Code:
        var = "filenameXYX.txt"
        open("dir1/dir2/%s" % (var))

        Comment

        • iamfletch
          New Member
          • Jan 2010
          • 18

          #5
          Yup, that's all clear now. Thanks a lot, fast and helpful forums here.

          Comment

          Working...