[Tutor] Files and file attributes

D-Man dsh8290@rit.edu
Wed, 21 Feb 2001 19:46:14 -0500


On Wed, Feb 21, 2001 at 05:55:11PM -0500, Pat/Bob Fisher wrote:
| 
|    I am pretty new at programming in Python, but have had experience in
|    programming in other languages.  I went through the tutorial which I
|    thought was fairly good, except the section on the methods of file
|    objects was pretty sparse.  It seems to me that dealing with files is
|    rather awkward. I have used the  list representation  filelist =
|    f.readlines() and then used the fine list methods to manipulate the
|    filelist, but I am having trouble getting a new file from  my new
|    filelist.  The g.write('string') gives me a whole lot of extraneous
|    stuff.

What kind of extraneous stuff?  f.readlines() gives you a list of
strings.  That list is completely independent of any files (except
that it happens to have originated from a file).

Use the dir() function on a file object in the interpreter to see all
the available functions of a file object.  Use
print fileobject.function.__doc__  to print the docstring.  (Or just
browse the library reference manual ;-))

If you use g.write( list_of_strings )  you will get "extra" stuff --
the visual representation of a list.  Use string.join() to concatenate
the strings in the list into a single string before writing it to a
file.

|    
|    Another problem I am having is trying  to open files in other
|    directories.  For example,
|    
|    
|    
|       f=open('C:\tmp\testfile','r+') just doesn't work for me.
                  ^^  ^^

These \t are tab characters, not \ followed by t.  IMO using \ to
delimit paths is evil, partly because it is inconsisten (POSIX/Unix
uses /) and more importantly because it is a special character in
strings in all the languages I've used (except for maybe Common Lisp).

One solution is to escape all \ in filename :

f = open( 'C:\\tmp\\testfile' , 'r+' )

or Python has a neat way of declaring a string as raw data :

f = open( r'c:\tmp\testfile' , 'r+' )

Also, I think tqs don't do any special character expansion :

f = open( """c:\tmp\testfile""" , 'r+' )

|    
|    Can anyone help, or at least tell me where I can learn more about file
|    manipulation?
|    
|    I suppose it is obvious I am using a windows platform, specifically
|    WindowsME.

Ugh.

|    

HTH,
-D