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


#WAP to show all names present in names.txt file
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 file
f=open("names.txt")
for l in f:
    print(l)
f.close











Comments

Popular posts from this blog

Converting Excel File to JSON File using xlrd module

Using Oracle with Python

Using time module