opening a file to read under windows

Tim Peters tim_one at email.msn.com
Sat Oct 9 21:54:54 EDT 1999


[dave hatton]
> ...
> How should I open a text file for reading under windows? (98 in this case)
>
> Every thing I try results in an error message which shows the filename
> correctly but with "\\" between each element not "\"
>
> I'm using "fd = open(filename, 'r')" where filename="c:\dir\file.txt"

It is much more helpful to post an actual code snippet and the actual error
message, rather than attempt to describe either.  You wouldn't believe how
ambiguous those descriptions are <wink>.

Here are 4 ways to open that work:

D:\Python>type example.txt
line 1
line 2

D:\Python>python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> f = open("example.txt")
>>> print f.readline()
line 1

>>> print f.readline()
line 2

>>> print f.readline()

>>> f.close()
>>> f = open("d:/python/example.txt")
>>> print f.readlines()
['line 1 \012', 'line 2 \012']
>>> f.close()
>>> f = open("d:\\python\\example.txt")
>>> print f.readlines()
['line 1 \012', 'line 2 \012']
>>> f = open(r"d:\python\example.txt")
>>> print f.readlines()
['line 1 \012', 'line 2 \012']
>>>

The most common mistakes under Windows:

1) Using backslashes naively in file paths; e.g. "\t" is a tab character,
not a backslash followed by a t.  "\\t" is a backslash followed by a t, as
is r"\t".

2) Opening binary files (for input or output) without explicitly specifying
binary mode.  Text mode and binary mode are different under Windows.

once-you-get-beyond-opening-closing-is-easy-ly y'rs  - tim






More information about the Python-list mailing list