Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - File Operation/Management

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Read the whole text file with single read() - Example 1
  • Read the file line by line with for loop - Example 2
  • Read the file line by line with while loop - Example 3
  • Write text into a file - Example 4

 

 

< Syntax >

  • file fHandle = open(file_name [, access_mode][, buffering])
  • fHandle.read()
  • fHandle.read(count)
  • fHandle.readline()
  • fHandle.write(string)
  • fHandle.write(integer)
  • fHandle.write(ListOfInteger)
  • fHandle.close()

 

Mode

Description

r

Read only.

rb

Read only in binary format

r+

Read and Write

rb+

Read and Write in binary format

w

Write only

wb

Write only in binary format

w+

Write and Read

wb+

Write and Read in binary format

a

Append

ab

Append in binary format

a+

Append and Read

ab+

Append and Read in binary format

 

 

< Examples >

 

Data File used in this example : Following is the contents in data file (in text format) that is used in following examples.

Since I would not specify path of the file, this file should be in the same folder as the example script file

 

< data.txt >

Line 1 : Data 1

Line 2 : Data 2

Line 3 : Data 3

Line 4 : Data 4

Line 5 : Data 5

 

 

< Example 1 >

 

fHandle = open("data.txt","r")

 

readStr = fHandle.read()

print(readStr)

 

fHandle.close()

 

Result :--------------------------------

 

Line 1 : Data 1

Line 2 : Data 2

Line 3 : Data 3

Line 4 : Data 4

Line 5 : Data 5

 

 

< Example 2 >

 

fHandle = open("data.txt","r")

 

for readStr in fHandle :

    print(readStr)

 

fHandle.close()

 

Result :--------------------------------

Line 1 : Data 1

 

Line 2 : Data 2

 

Line 3 : Data 3

 

Line 4 : Data 4

 

Line 5 : Data 5

 

 

< Example 3 >

 

fHandle = open("data.txt","r")

 

while 1:

    readStr = fHandle.readline()

    if not readStr:

        break

    print(readStr)

 

fHandle.close()

 

Result :--------------------------------

Line 1 : Data 1

 

Line 2 : Data 2

 

Line 3 : Data 3

 

Line 4 : Data 4

 

Line 5 : Data 5

 

 

< Example 4 >

 

fHandle = open("output.txt","w")

 

for i in range(1,5) :

   fHandle.write("Line "+str(i)+"\n")

 

fHandle.close()

 

Result :--------------------------------

You should see output.txt file is created with following contents

Line 1

Line 2

Line 3

Line 4