Skip to content Skip to sidebar Skip to footer

When Reading a File in Python, You Must Specify Two Items

On this page: open(), file.read(), file.readlines(), file.write(), file.writelines().

Before proceeding, brand sure you understand the concepts of file path and CWD. If you run into problems, visit the Mutual Pitfalls section at the lesser of this page.

Opening and Closing a "File Object"

As seen in Tutorials #15 and #sixteen, file IO (input/output) operations are done through a file data object. Information technology typically gain as follows:
  1. Create a file object using the open() function. Along with the file name, specify:
    • 'r' for reading in an existing file (default; tin can exist dropped),
    • 'westward' for creating a new file for writing,
    • 'a' for appending new content to an existing file.
  2. Do something with the file object (reading, writing).
  3. Close the file object by calling the .close() method on the file object.
Below, myfile is the file data object we're creating for reading. 'alice.txt' is a pre-existing text file in the same directory as the foo.py script. After the file content is read in, .close() is called on myfile, closing the file object.
myfile = open up('alice.txt',              'r')       myfile.close()                                    foo.py            
Below, myfile is opened for writing. In the second case, the 'a' switch makes sure that the new content is tacked on at the cease of the existing text file. Had you used 'w' instead, the original file would accept been overwritten.
myfile = open up('results.txt',              'westward')     myfile.close()                        myfile = open('results.txt',              'a')     myfile.close()                                    foo.py            

Reading from a File

OK, we know how to open up and shut a file object. Only what are the actual commands for reading? There are multiple methods.

First off,

.read() reads in the unabridged text content of the file as a single string. Below, the file is read into a variable named marytxt, which ends up being a string-type object. Download mary-short.txt and attempt out yourself.
                      >>>                      f = open('mary-curt.txt')                      >>>                      marytxt = f.read()                                   >>>                      f.shut()                      >>>                      marytxt                      'Mary had a little lamb,\nHis fleece was white as snowfall,\nAnd everywhere that Mary  went,\nThe lamb was certain to get.\due north'                      >>>                      type(marytxt)                                        <blazon 'str'>                      >>>                      len(marytxt)                                         110                      >>>                      print marytxt[0]                      Yard                    
Side by side, .readlines() reads in the entire text content of the file as a list of lines, each terminating with a line break. Beneath, you can run into marylines is a list of strings, where each string is a line from mary-brusque.txt.
                      >>>                      f = open up('mary-brusque.txt')                      >>>                      marylines = f.readlines()                            >>>                      f.close()                      >>>                      marylines                      ['Mary had a piddling lamb,\n', 'His fleece was white as snow,\north', 'And everywhere  that Mary went,\northward', 'The lamb was sure to go.\due north']                      >>>                      blazon(marylines)                                      <type 'list'>                      >>>                      len(marylines)                                       4                      >>>                      impress marylines[0]                      Mary had a little lamb,                                          
Lastly, rather than loading the entire file content into memory, you can iterate through the file object line by line using the for ... in loop. This method is more than memory-efficient and therefore recommended when dealing with a very big file. Below, bible-kjv.txt is opened, and whatsoever line containing smite is printed out. Download bible-kjv.txt and try out yourself.
f = open up('bible-kjv.txt')      for line in f:                     if              'smite'              in line:          print line,                  f.shut()              foo.py            

Writing to a File

Writing methods also come in a pair: .write() and .writelines(). Like the corresponding reading methods, .write() handles a single string, while .writelines() handles a listing of strings.

Below,

.write() writes a single string each time to the designated output file:
                      >>>                      fout = open('hullo.txt',                      'westward')                      >>>                      fout.write('Hello, earth!\due north')                                      >>>                      fout.write('My proper name is Homer.\n')                      >>>                      fout.write("What a beautiful mean solar day we're having.\north")                      >>>                      fout.shut()                    
This time, nosotros have tobuy, a list of strings, which .writelines() writes out at once:
                      >>>                      tobuy = ['milk\n',                      'butter\due north',                      'coffee beans\north',                      'arugula\n']                      >>>                      fout = open('grocerylist.txt',                      'due west')                      >>>                      fout.writelines(tobuy)                                            >>>                      fout.close()                    
Notation that all strings in the examples have the line break '\n' at the end. Without it, all strings will be printed out on the same line, which is what was happening in Tutorial 16. Dissimilar the print argument which prints out a string on its own new line, writing methods will not tack on a newline character -- you must think to supply '\n' if you lot wish a string to occupy its own line.

Common Pitfalls

File I/O is notoriously fraught with stumbling blocks for beginning programmers. Below are the nigh mutual ones.

"No such file or directory" fault

                      >>>                      f = open('mary-brusque.txt')                      Traceback (most recent phone call last):   File "", line 1, in                                                      IOError: [Errno i] No such file or directory: 'mary-short.txt'                                                                  
You lot are getting this fault because Python failed to locate the file for reading. Make sure you are supplying the right file path and name. Read starting time File Path and CWD. Besides, refer to this, this and this FAQ.

Entire file content can exist read in but One time per opening

                      >>>                      f = open('mary-short.txt')                      >>>                      marytxt = f.read()                                 >>>                      marylines = f.readlines()                          >>>                      f.shut()                      >>>                      len(marytxt)                      110                      >>>                      len(marylines)                           0                    
Both .read() and .readlines() come with the concept of a cursor. After either control is executed, the cursor moves to the end of the file, leaving nothing more to read in. Therefore, one time a file content has been read in, another attempt to read from the file object will produce an empty information object. If for some reason yous must read the file content again, you must close and re-open the file.

But the string type tin can be written

                      >>>                      pi = three.141592                      >>>                      fout = open('math.txt',                      'westward')                      >>>                      fout.write("Pi's value is ")                      >>>                      fout.write(pi)                                      Traceback (most recent call last):   File "", line 1, in                                                      TypeError: expected a character buffer object                                                                    >>>                      fout.write(str(pi))                                >>>                                          
Writing methods merely works with strings: .write() takes a single string, and .writelines() takes a list which contains strings simply. Not-string type data must be first coerced into the cord type by using the str() function.

Your output file is empty

This happens to everyone: y'all write something out, open up the file to view, just to find it empty. In other times, the file content may be incomplete. Curious, isn't it? Well, the cause is simple: Yous FORGOT .close(). Writing out happens in buffers; flushing out the concluding writing buffer does non happen until you lot close your file object. ALWAYS REMEMBER TO Shut YOUR FILE OBJECT.

(Windows) Line breaks do not bear witness up
If you open up your text file in Notepad app in Windows and see everything in one line, don't be alarmed. Open the same text file in Wordpad or, even better, Notepad++, and you will see that the line breaks are there later all. See this FAQ for details.

robinsonwirave1956.blogspot.com

Source: https://sites.pitt.edu/~naraehan/python2/reading_writing_methods.html

إرسال تعليق for "When Reading a File in Python, You Must Specify Two Items"