Python Reading Text Files and Writing

Text files are important for applications. The most common use of Text files is to store output of programs. The text files can also be processed in programs to do analysis of the text content or use the data stored for other processing.  A text file usually contains printable characters, spaces, and other special characters that can be punched in from the keyboard. So, here is all about Python Reading Text Files you need to know.

Python Reading Text Files Functions

open( file_name, file_open_mode)

This function is called with two arguments. First argument is the file name. Second argument is file open mode. This function returns the handle of the file opened. Subsequent file handling functions in the program are executed using this handle until the file is closed with close function.  You can create multiple file handlers to open different text files for simultaneous processing.

If the file name exists then the file handle on the left of the assignment operator gets the file handle. If the file does not exist, an error is generated. By default file is searched in the current folder. If you are referring to a file at a specific location, you need to give the qualified file name (path and file name)

Modes of opening file are

  • w            for writing into file
  • r              for reading from file
  • r+            for writing and reading a file
  • a              for appending in a file

close()

Close function closes the file opened with open() function. If no file is opened this function generates an error. It is a good practice to close a file after its use to release the resources allocated to the file. A file once closed can be used again after opening with open() function. You can close and open files as many times as you wish.

write(text_string)

This function is used to store text in the text file opened in write mode. The text string is stored in the file as it is. If you want to store text as paragraph then you can use the ‘\n’ (new line character) in text to separate them.

read([number-of-characters to read])

read() function reads group of characters from the file. If the function is called with empty parenthesis then entire contents of a file are read in one go. The text read from the file can be stored in a variable as string. If you want to read specific number of characters you can mention the count as integer value in parenthesis.

readline()

readline() function reads the text file content one line at a time.  The lines are separated by newline character.

Example

Open a file in write mode and close it. Open the same file in read mode to print text stored in the file using read() function.

fh= open("myfile.txt","w")  #open file in write mode
fh.write("hello this is the content.\nwriting more.\nand more\n")  # writing newline separated text in file
fh.close()   # closing the file
fh= open("myfile.txt","r")  #open file in read mode
print(fh.read())   #read all contents of the file

Output

Example

Open a file in write mode and close it. Open the same file in read mode to print line-wise text stored in the file using readline() function and while loop. The loop must be terminated when reading further returns blank character.

fh= open("myfile.txt","w")  #open file in write mode
fh.write("hello this is the content.\nwriting more.\nand more")# writing newline separated text in file
fh.close() # closing the file
fh= open("myfile.txt","r")#open file in read mode
while 1:
    curtext= fh.readline();
    if curtext=="":
        break
    else:
        print(curtext[0:len(curtext)-1])

Output

Python Reading Text FIles

Example

Open an existing text file in read mode. Using while  loop and read() function print contents in block of 30 characters per line. While Loop must be terminated when reading further returns blank character.

fh= open("myfile.txt","r")#open file in read mode
while 1:
    curtext= fh.read(30) #read 30 characters from file and save in variable
    if curtext=="":
        break
    else:
        print(curtext)

Output

Python Reading text file using read function

Example

Open an existing text file in read mode. Using split function and  a white-space as word separator, store all the words of the file in an array as  its elements. Check each word in this array, using For loop and len() function, for its length. Count the words as one character, two character, three characters, four characters and five or more characters. The final count of words in each category should be printed.

fh= open("myfile.txt","r")#open file in read mode
curtext=fh.read();
txtArr=curtext.split(" ")
onechar=0
twochar=0
threechar=0
fourchar=0
fiveplus=0

for i in range(len(txtArr)):
    if len(txtArr[i])==1:
         onechar=onechar+1
    elif len(txtArr[i])==2:
        twochar=twochar+1
    elif len(txtArr[i])==3:
        threechar=threechar+1
    elif len(txtArr[i])==4:
        fourchar=fourchar+1
    else:    
        fiveplus=fiveplus+1
print("The character count of words in file")        
print("1 char=",onechar,", 2 char=",twochar,",  3 char=", threechar,",  4 char=", fourchar,",  5 words=",fiveplus)    
   

Output

count words of different length Python text file

Python Reading Text Files and writing into them can be easily done with the functions discussed above. The examples show different ways of implementing Python reading text files.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *