Home » Python

Python | Rename an existing file (Example of os.rename() method)

os.rename() method in python: Here, we are going to learn how to rename an existing file in python?
Submitted by IncludeHelp, on December 30, 2018

Renaming an existing file

To change the name of an existing file – we use "rename()" method of "os" module – so to access the "rename()" method, we must have to import the module "os".

Module import statement: import os

Syntax of rename() method: os.rename(src, dest)

Here, src is the name to the source file (old file) and dest is the name of the destination file (new file name).

Example:

Here is the code to change the name of an existing filename in python... In this example, we are creating a file file1.txt and writing "Hello" in it, then, we are closing the file, renaming file1.txt to myfile.txt. To verify the operations, checking file1.txt exists or not – if file1.txt does not exist, checking myfile.txt if it exists – printing its content and the content will be 'Hello" – which we have written in file1.txt.

import os

def main():
	# creating a file first
	fo = open("file1.txt","wt")
	# writing data in it
	fo.write("Hello")
	# closing the file
	fo.close()

	# changing the file name
	os.rename("file1.txt", "myfile.txt")

	# checking that file1.txt exists or not
	# if does not exist - will open myfile and read
	if not(os.path.exists("file1.txt")):
		print("file1.txt does not exist.")
		# checking myfile, and read its content 
		if os.path.exists("myfile.txt"):
			print("myfile.txt exists, reading its content...")
			# opening file
			fo = open("myfile.txt", "rt")
			# reading its content
			str = fo.read()
			# printing the content 
			print("Content of the file: ")
			print(str)
	else:
		print("Operation failed.")
	
if __name__=="__main__":main()

Output

file1.txt does not exist.
myfile.txt exists, reading its content...
Content of the file: 
Hello



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.