<< Chapter < Page Chapter >> Page >

Open a text file for writing

Listing 1 calls the built-in function named open to create and return a file object in write mode . The reference to the file object is stored in the variable named theFile . The write mode is indicated by the "w" as the second parameter to the open function. The description of the open function at The Python Standard Library -- 2. Built-in Functions describes eight different modes that can be specified when a file object is created. The program in this module will use the following three modes:

  • 'w' -- open for writing, truncating the file first
  • 'r' -- open for reading (default)
  • 'a' -- open for writing, appending to the end of the file if it exists
Listing 1 . Open a text file for writing.
#Open a file object for writing. theFile = open("SampleTextFile.txt","w")

Write text and close the file

Listing 2 calls the write method five times in succession to write five strings into the file.

Listing 2 . Write text and close the file.
#Write several lines of text to the file. Note the requirement to explicitly #provide the newline at the end of each line of text.theFile.write("This is a sample text file.\n") theFile.write("Second line of text.\n")theFile.write("Third line.\n") theFile.write("Fourth line.\n")theFile.write("Last line.\n") #Be sure to close the filetheFile.close()

Once you have a file object, there are a variety of methods that you can call on that object, one of which is the method named write . The best description that I could find for that set of methods is located at File Objects , which is part of the documentation for Python version 2.3. (Hopefully it is still correct for Python version 3.)

That document provides the following description for the write method:

Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

Listing 2 calls the close method on the file after the strings are written to the file to ensure that the data is actually moved from the output buffer intothe file. The description of the close method at File Object reads as follows:

Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.

Read and print the file contents with a for loop

Listing 3 shows one way to read the contents of a text file, line-by-line, using a for loop as an iterator. Note that the "r" mode is the default but it is shown here for clarity.

Listing 3 . Read and print the file contents with afor loop.
#Open the file object in read mode. theFile = open("SampleTextFile.txt","r")#Read and print the lines of text. for line in theFile:print(line,end='') #Close the filetheFile.close()

The output produced by the code in Listing 3 is shown in Figure 1 . As you can see, the output matches the text written into the file in Listing 2 .

Figure 1 . Output from the code in Listing 3.
This is a sample text file. Second line of text.Third line. Fourth line.Last line.

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Itse 1359 introduction to scripting languages: python. OpenStax CNX. Jan 22, 2016 Download for free at https://legacy.cnx.org/content/col11713/1.32
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Itse 1359 introduction to scripting languages: python' conversation and receive update notifications?

Ask