Home >Backend Development >Python Tutorial >How to Rename a File in Python?

How to Rename a File in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 07:36:09781browse

How to Rename a File in Python?

Renaming Files with Python

Question: How to rename a file named a.txt to b.kml using Python?

Answer:

To rename files in Python, utilize the os.rename() function. It takes two arguments: the current file path and the desired new file path.

import os

# Rename 'a.txt' to 'b.kml'
os.rename('a.txt', 'b.kml')

Usage:

The syntax for os.rename() is:

os.rename('from.extension.whatever','to.another.extension')

Where:

  • from.extension.whatever represents the current file path and filename with its extension.
  • to.another.extension represents the desired new file path and filename with the new extension.

The above is the detailed content of How to Rename a File in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn