Help with reading file in windows.

anandpillai member29923 at dbforums.com
Wed May 21 02:28:01 EDT 2003


The first solution had a problem in the 2nd line

  => reading_file = open(asking).r

  This is wrong syntax since you need to say
   'open(asking, 'r') . The mode for opening is given
   as second argument to open() in quotes.

  The second solution also had a problem in the 2nd line

   => reading_file = file(asking).read()

    You are trying to call read() on something which is
     not a 'file' object. There is no method  'file()' in python
     which takes a string as argument to open a file.

  To read from a file you need to first create a file object.
  You do it by calling the 'open()' method on a file name string and
  passing a mode as second argument.  The mode is 'r' (read text mode)
  by default. So your basic file opening would be like,

  f = open(asking)
  data = f.read()

  For writing you pass 'w', for reading binary 'rb', read & write, 'rw'
  , writing binary 'wb' etc.  The try ... except
  clauses are there to catch any possible exceptions like file
  not found, unable to open etc.

  You can get a better understanding of this method by
  looking up the documentation of the 'fopen' function in
   ANSI C. This method signature is very similar to the
  'fopen' C function. To do that try 'man fopen' on a unix
   or linux box or an a windoze machine with MKS tools
   installed.

Anand Pillai

--
"The Python Guy"


Posted via http://dbforums.com




More information about the Python-list mailing list