2

I'm a beginner trying to open a file as part of a function where the file name/path is the variable in the function. I've written one but am getting an error on a similar function. Here's the function code:

def read_board(board_file):
    """ (file path) -> list of str

    Return a board read from open file board_file. 

    >>>read_board('C:\Python33\Doc\theboard1.txt') 
    """

    bo_file = open(board_file, 'r')
    lines = bo_file.readlines()

    return lines

I'm getting this error

OSError: [Errno 22] Invalid argument: 'C:\Python33\Doc\theboard1.txt'

The path is correct (triple checked) and I'm using that example to test the file read.

msw
  • 42,753
  • 9
  • 87
  • 112

3 Answers3

2

You need to use double backslash the escape the backslash, the following will work:

read_board('C:\\Python33\\Doc\\theboard1.txt')

This is so that python treats the second \ as a literal and doesn't not use it as an escape character for the character after it as in your case.

sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • thanks, got it working now. not sure how the other one called anything but i'm on track. – sharkys machine Apr 28 '14 at 03:46
  • @sharkysmachine: To be more explicit, the `\t` in your path was converted to the tabulator character. Try to print your original string where backslashes were not doubled (and when the string literal is not marked as `r'raw string literal'`). – pepr Apr 28 '14 at 06:47
2

I'd normally suggest using os.path.join but since Windows paths are so brain damaged anyway, that's not going to help much.¹

One way to get it right is to use the raw Python string which doesn't interpret backslashes:

open(r'c:\stupid\junk.txt')

or just pretend that DOS was a bad dream and use forward slashes like god intended:

open('c:/stupid/junk.txt')

¹exercise for the reader: what does os.path.join('c:', 'junk.dat') return? Is it different behavior than than `os.path.join('stupid', 'junk.txt')? Has this been a confusion for a while?

Community
  • 1
  • 1
msw
  • 42,753
  • 9
  • 87
  • 112
0

And you Can Using ::

os.sep

Between Files like

("C:"+os.sep+"user")

After importing os module

saudi_Dev
  • 829
  • 2
  • 7
  • 11