Python File Handling

We can use Python File handling to read and write data to and from the file.

Let us understand this step by step.

  1. Create a file in Python
  2. Open the file
  3. Writing data to a file
  4. Reading data from a file
  5. Append data to file
  6. Loop through the data in a file
  7. Overwrite a particular line
  8. Delete a file
  9. Copy data from one text file to another

How to work with files in Python – File Handling

First, we need to open the file.




f = open(filename, mode)

After we have finished reading/writing to the file you need to close the file using close() method

f.close() #where f is a file pointer

Writing data to the file

f=open("c:\\data\\Test.txt","w")
sname=input("Enter your name:")
sno=input("Enter sno")
mark=input ("Enter mark")
s=" \n "+ sname+"    "+sno+"    "+mark
f.write(s);
print("File created")
f.close()
f=open("c:\\data\\Test.txt","r")
print("The contents of the file")
print(f.read())
f.close();

Method 2-

f=open("c:\\data\\Test.txt","w")
f.write("sname          sno    mark \n");
choice="y"

while(choice=="y"):
    sname=input("Enter your name:")
    sno=input("Enter sno")
    mark=input ("Enter mark")
    s=sname+"    "+sno+"    "+mark+"\n"
    f.write(s);
    choice=input("Do you want continue y/n")
    if(choice=="n"):
        break;

print("File created")
f.close()
f=open("c:\\data\\Test.txt","r")
print("The contents of the file")
#print("sname    sno     mark")
print(f.read())
f.close();

Reading data from the file

You may also read: How to read a specific line from a text file in Python

f = open('myfile.txt', 'r')
print(f.read())
f.close()

Appending data to the file

f = open('myfile.txt', 'a')
f.write("this is third line\n")
f.close()

Looping through the data using for loop

f = open('myfile.txt', 'r')
for line in f:
print(line)
f.close()

How to read the files

def main():
f=open("call.py","r")
f1=f.readlines();
for x in f1:
print(x)

if __name__ == "__main__":
main()

Read and write the data file accept input values from keyboard

f = open('myfile.txt', 'w')
str="y";
while(str=="y"):
        s=input("Enter any string")
        f.write(s)
        f.write("\n")
        print("want to continue press y or n");
        str=input("enter your choice");
        
f.close()

f=open("myfile.txt","r")
f1=f.read();
print(f1)        
f.close();

How to write and Read the data file

def main():
     f= open("abc.txt","w")
     #f=open("abc.txt","a")
     for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
     f.close()   
   #  Open back the file and read the contents
     f=open("abc.txt", "r")
     if f.mode == 'r':
         contents =f.read()
         print (contents)

     
if __name__== "__main__":
  main()

 

How to overwrite a particular line in Python

def replace_line(file_name, line_num, text):
    f= open("abc.txt","w")
    for i in range(10):
        f.write("This is line %d\r" % (i+1))
    f.close()   
    lines = open(file_name, 'r').readlines()
    lines[line_num] =  text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()
    f=open(file_name,"r")
    print(f.read())
if __name__=="__main__":
        replace_line("abc.txt",4,"god is great\n")

 Delete the file

import os
os.remove("cba.xml")
print("File deleted");

The With Statement

The with statement can be used while opening a file. We can use this to group file operation statements within a block.

The Advantage of with statement is it will take care closing of file, after completing all operations automatically even in the case of exceptions and we are not required to close explicitly.

with open ("abc.txt","w") as f:
f.write("God is Great\n")
f.write("Time is gold\n")
f.write("Have nice day\n")
print("is File Closed",f.closed)
print("is File Closed",f.closed)

How to Copying from one text file to another file?

f = open('c:/data/abc.txt')
f1 = open('c:/data/abc1.txt', 'a')
for line in f.readlines():
    f1.write(line)
print("file copied")

f1.close()
f.close()

Write a program to check whether the given file exists or not, if available then print its content

import os,sys
fname=input("Enter filename:")
if os.path.isfile(fname):
    print("File exists:",fname)
    f=open(fname,"r")
else:
    print("File does not exists:",fname)
    sys.exit(0)
print("The Contents of file is:")
data=f.read()
print(data)

 


Leave a Reply

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