File Handling in Python
File and folder Related Functions
Use os module
os.rename(oldname,newname) rename file or folder
os.remove(filename) remove a file
os.mkdir(dirname) make directory
os.rmdir(dirname) remove a directory
os.chdir(dirname) change directory
os.getcwd() returns current working directory
Creating a text file
#WAP to input few names from user and save into a file names.txt#until end get pressed
f=open("names.txt","w")
while True:
name=input("Enter a name : ")
if name.lower()=="end":
break
f.write(name)
f.write("\n")
f.close()
print("File Created")
Reading all data in one go
f=open("names.txt")
names=f.read()
print(names)
f.close()
Reading all data line by line
#WAP to show all names present in names.txt filef=open("names.txt")
for l in f:
print(l)
f.close
Comments
Post a Comment