Python File Operations

Containing Strings To store a group of strings into a text file, we have to use the write() method inside a loop. For example, to store strings into the file as long as the user does not type '@' symbol, we can write while loop as:

File write operation

CopiedCopy Code

while str != '@': 
   #write the string into file 
   if(str != '@'): 
      f.write(str+"\n")

Please observe the "\n" at the end of the string inside write() method. The write() method writes all the strings sequentially in a single line. To write the strings in different lines, we are supposed to add "\n" character at the end of each string.

A Python program to store a group of strings into a text file.

CopiedCopy Code

f = open('myfile.txt', 'w') 
print('Enter text (@ at end):') 
while str != '@': 
   str = input() 
   if(str != '@'): 
     f.write(str+"\n") 
f.close()

File read operation

Now, to read the strings from the "myfile.txt", we can use the read() method in the following way:

f.read()

This method reads all the lines of the text file and displays them line by line as they were stored in the "myfile.txt".

A Python program to read all the strings from the text file and display them.

CopiedCopy Code

f = open('myfile.txt', 'r') 
print('The file contents are:') 
str = f.read() 
print(str) 
f.close()
						

File append operation

f = open('myfile.txt', 'a+')

Once the file is opened in 'a+' mode, as usual we can use write() method to append the strings to the file. After writing the data, without closing the file, we can read strings from the file. But first of all, we should place the file handler to the beginning of the file using seek() method as:

f.seek(offset, fromwhere)

Here, 'offset' represents how many bytes to move. 'fromwhere' represents from which position to move. For example, 'fromwhere' is 0 represents from beginning of file, 1 represents from the current position in the file and 2 represents from the ending of file.

f.seek(10, 0)

This will position the file handler at 10th byte from the beginning of the file. So, any reading operation will read data from 10th byte onwards.

f.seek(0, 0)

This will position the file handler at the 0th byte from the beginning of the file. It means any reading operation will read the data quite from the beginning of the file.

A Python program to append data to an existing file and then displaying the entire file.

CopiedCopy Code

f = open('myfile.txt', 'a+') 
print('Enter text to append(@ at end):') 
while str != '@': 
   str = input() 
   if(str != '@'): 
     f.write(str+"\n") 
#put the file pointer to the beginning of file 
f.seek(4,0) 
#read strings from the file 
print('The file contents are:') 
str = f.read() 
print(str) 
#closing the file 
f.close()