Home > Common Problem > body text

How to rename files in python

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-10-12 10:02:24
Original
2817 people have browsed it

You can use the "os.rename()" function to rename files in Python. The steps are: 1. Import os; 2. Set the original file variable name "old_name"; 3. Set the new file variable Named "new_name"; 4. Use "os.rename(old_name,new_name)" to rename.

How to rename files in python

# Operating system for this tutorial: Windows 10 system, Dell G3 computer.

In Python, you can use the os.rename() function to rename files. Here is a simple example:

import os
# 原始文件名
old_name = 'old_file.txt'
# 新文件名
new_name = 'new_file.txt'
# 重命名文件
os.rename(old_name, new_name)
Copy after login

In the above example, we call os.rename() by specifying the original file name old_name and the new file name new_name function to rename files. This will rename old_file.txt to new_file.txt.

Please note that when the os.rename() function renames a file, it will overwrite the target file (if it exists). Therefore, make sure that the new filename does not duplicate an existing filename to avoid accidental overwrites or errors.

In addition, you can also use the shutil.move() function to implement file renaming, which provides more flexibility and functionality. Below is an example of shutil.move():

import shutil
# 原始文件路径
old_path = '/path/to/old_file.txt'
# 新文件路径
new_path = '/path/to/new_file.txt'
# 重命名文件
shutil.move(old_path, new_path)
Copy after login

In this example, we use shutil.move() function to move and rename files by specifying The original file path old_path and the new file path new_path are used to complete the renaming operation.

The above is the detailed content of How to rename files in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!