Page 1 of 1

Reading and Writing to a .txt File in Python

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1252
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 03 November 2010 - 08:08 AM

Let's see how Python can be used to read and write text files. Python makes things very easy for us and you'll be amazed at how simple things can be.

I'll be using Python 2.x for this brief tutorial.

First lets start with Reading a text file.

Reading a Text File

Let's create a new object to handle out connection to the file:


f = open("C:/Test.txt", "r");
print f
#Output:
#<open file 'C:/Test.txt', mode 'r' at 0x01275A18>



I'm giving the open() method, two arguments: the location of the file we want to read, and the mode we want to use. There are 3 basic modes you're going to want to remember:

  • R - when the file will only be read.
  • W - when you want to write to the file.
  • A - opens the file for appending, any data you write will be added to the end of the file.


The mode argument is optional and if you leave it out, it will use R as the default.

Let's read the contents on my text file called "Test.txt".

f = open("C:/Test.txt", "r");
print f

for line in f.readlines():
    print line
#Output:
#<open file 'C:/Test.txt', mode 'r' at 0x01735A18>
#Sergio

#Tapia

#Gutierrez


We're using Pythons built in for loop that acts similarly to C# foreach loop. Notice that it prints each line, and adds a newline in between. If you want to print the file contents exactly as they appear in the file itself, just add a comma at the end of the print line statement and you're off.


f = open("C:/Test.txt", "r");
print f

for line in f.readlines():
    print line,
#Output:
#<open file 'C:/Test.txt', mode 'r' at 0x01735A18>
#Sergio
#Tapia
#Gutierrez



There are also the following ways of reading a text file:


f = open("C:/Test.txt", "r");
print f

#Prints out the entire file.
print f.read()

#Prints out the contents, line by line.
print f.readline()
print f.readline()
print f.readline()

#Returns a list containing all of the lines
#in the text file.
myLines = f.readlines()

for line in myLines:
    print line



Writing to a Text File

You can use the write() method to write a string to a file. Don't forget to use the mode <strong>W</strong> otherwise the file won't be written.

f = open("C:/Test.txt", "w");
print f

f.write("My writing test!")


Be careful when using this because it completely erases the contents of the existing file, and overwrites anything with the string you use. If you want to conserve the information in the text file, use mode <strong>A</strong>.

f = open("C:/Test.txt", "a");
print f

f.write("My writing test!\n")


Anything you want to write to a file has to be converted to a string first!

f = open("C:/Test.txt", "a");
print f

value = ('My name is', "Sergio")
myString = str(value)

f.write(myString)


Once you're done using the file, remember to close the connection.

f = open("C:/Test.txt", "a");
print f

value = ('My name is', "Sergio")
myString = str(value)

f.write(myString)

f.close()



If you're familiar with C#, you'll know that it's good practice to use a Using statement with things like file IO or database connections. The same applies to Python!

with open('C:/Text.txt', 'a') as f:
    f.write("using statements baby!")



------------------------------------------------------

If you liked this tutorial, you can read more articles written by me at my blog. Visit AlphaOT

Is This A Good Question/Topic? 4
  • +

Replies To: Reading and Writing to a .txt File in Python

#2 k3y  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 205
  • Joined: 25-February 12

Posted 17 July 2012 - 02:08 PM

mod: excessive quote removed

Great little tutorial (I bookmarked it). However; I would have <3d to have seen some more examples of how to use some exception handling as well as more examples on how with works

This post has been edited by modi123_1: 17 July 2012 - 02:21 PM
Reason for edit:: removed giant quote

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1