file handling
file handling
O/P:
Hi this is Python programming
Lets Learn Python.
f=open("file.txt",'r')
print(f.read())
O/p:
FileNotFoundError: [Errno 2] No such file or
directory: 'file.txt'
Read Lines
• We can return one line by using the readline() method.
• f = open("demofile.txt", "r")
print(f.readline())
O/P:Hi this is Python programming
• By looping through the lines of the file, you can read the whole file,
line by line
• f = open("demofile.txt", "r")
for x in f:
print(x)
O/P:
Hi this is Python programming
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Renaming a file
import os
os.rename('C:/Users/ASUS/Desktop/jupyter
projects/hi.txt', 'C:/Users/ASUS/Desktop/jupyter
projects/bye.txt'
Insertion in a text file
f=open("demofile.txt","r")
lines = f.readlines()
print(lines)
lines.insert(1, "Hi this is new
txt")
f=open("File1.txt","w")
f.writelines(lines)