rename the file in python by R4R Team

- rename() is a operating system function in python which are able to rename the files and directories

Syntax-

os.rename(oldfilename,newfilename)


program-

import os

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

os.rename('oldfile.txt','newfile.txt')


output-

This is the file


-In this program, we have a file named as 'oldfile.txt' that contain the text "This is the file" so we read that file and close then we change the name of file from 'oldfile.txt' to 'newfile.txt'

-Now we try to print the content of newfile.txt

program-

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


output-

This is the file


-In this program, we open a old file with new name.
-If we try to open a file with old name then ?


program-

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


output-

f=open('oldfile.txt','r')

FileNotFoundError: [Errno 2] No such file or directory: 'oldfile.txt'




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!