Example HTML page

Renaming and Deleting files

Renaming and deleting the files

In this section I would like to describe how to rename and delete a file. For this Python provides two methods namely:

1.The rename( ) method

2. The remove( ) method

1. The rename( ) method

In general we will rename a file by right clicking on the required file and choose rename. Then we can rename it as we need.

Syntax

os.rename(‘Current_file_name’,’Old_file_name’)

In Python we can do file renaming through IDLE. Let us see how:

Ex Before renaming a file the following are the basic operations to be done.

>>> os.chdir(‘C:\python’)                             #Give your path

>>> os.getcwd( )

‘C:\\python’

>>> file=open(‘thefile.txt’,’wb+’)                #Opening a file(if it not exists it creates)

>>> file=open(‘thefile.txt’,’w’)

>>> file.write(“A test on file renaming”)   #Writing into the file

23

>>> file=open(‘thefile.txt’,’r’)

>>> file.read( )                                              #Reading from the file

‘A test on file renaming’

If you try to rename the file now you will get the following error.

>>> os.rename(“thefile.txt”,”thefilenew.txt”)

Traceback (most recent call last):

File “<pyshell#25>”, line 1, in <module>

os.rename(“thefile.txt”,”thefilenew.txt”)

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: ‘thefile.txt’ -> ‘thefilenew.txt’

The reason is that the file we took here is not closed. So the interpreter considers that this file is being used by the other. Hence we need to close the file and then we can rename it.

>>> file.close( )

>>> file.closed

True

>>> os.rename(“thefile.txt”,”thefilenew.txt”)

>>>

It prints nothing.

2.The remove( ) method

This method deletes the file which is specified as an argument.

Syntax

os.remove(file_name)

Ex

>>> os.remove(“thefilenew.txt”)

>>> os.remove(“thefile.txt”)

Traceback (most recent call last):

File “<pyshell#66>”, line 1, in <module>

os.remove(“thefile.txt”)

FileNotFoundError: [WinError 2] The system cannot find the file specified: ‘thefile.txt’

Here you will be displayed an error if you try to remove the old file since it is renamed.

 

 

 

 

 

Example HTML page

Leave a Reply

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

Pin It on Pinterest