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


当前回答

使用os.rename。但是你必须把两个文件的完整路径传递给函数。如果我的桌面上有一个。txt文件那么我就会这样做,而且我也必须给出一个完整的重命名文件。

os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')

其他回答

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

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

这里需要注意的一点是,我们应该检查是否存在具有新文件名的文件。

假设b.kml文件存在,那么重命名其他具有相同文件名的文件会导致删除现有的b.kml。

import os

if not os.path.exists('b.kml'):
    os.rename('a.txt','b.kml')

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

操作系统。重命名(旧的,新的)

这可以在Python文档中找到:http://docs.python.org/library/os.html

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)