我想把a.txt改为b.kml。


当前回答

import shutil

shutil.move('a.txt', 'b.kml')

这将用于重命名或移动文件。

其他回答

使用Pathlib库的路径。用Rename代替os.rename:

import pathlib

original_path = pathlib.Path('a.txt')
new_path = original_path.rename('b.kml')
import os

# Set the path
path = 'a\\b\\c'  
# save current working directory
saved_cwd = os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)
os.rename('a.txt', 'b.klm')
# moving back to the directory you were in 
os.chdir(saved_cwd)

文件可能在目录中,在这种情况下指定路径:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

os.chdir (r D: \ Folder1 \ Folder2) os.rename (src, dst) #src和dst应该在Folder2中

你可以使用os。系统调用终端来完成任务:

os.system('mv oldfile newfile')