我想把a.txt改为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 shutil

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

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

如果你正在使用Windows,你想重命名文件夹中的1000s文件,然后: 您可以使用下面的代码。(Python3)

import os

path = os.chdir(input("Enter the path of the Your Image Folder :  ")) #Here put the path of your folder where your images are stored

image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have

i = 0

for file in os.listdir(path):

    new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
    os.rename(file,new_file_name)

    i = i + 1

input("Renamed all Images!!")

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

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

import os

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

使用os.rename:

import os

os.rename('a.txt', 'b.kml')

用法:

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

从Python 3.4开始,可以使用pathlib模块来解决这个问题。

如果您使用的是旧版本,则可以使用这里提供的反向移植版本

让我们假设你不是在根路径(只是增加一点难度),你想重命名,并必须提供一个完整的路径,我们可以看看:

some_path = 'a/b/c/the_file.extension'

所以,你可以用你的路径创建一个path对象:

from pathlib import Path
p = Path(some_path)

为了提供一些关于这个物体的信息,我们可以从中提取一些东西。例如,如果出于某种原因,我们想通过将文件名从the_file修改为the_file_1来重命名文件,那么我们可以得到文件名部分:

name_without_extension = p.stem

并且仍然握着分机:

ext = p.suffix

我们可以通过简单的字符串操作来执行修改:

Python 3.6及更高版本使用f-strings!

new_file_name = f"{name_without_extension}_1"

否则:

new_file_name = "{}_{}".format(name_without_extension, 1)

现在我们可以对创建的path对象调用rename方法并附加ext来执行重命名,以完成我们想要的正确重命名结构:

p.rename(Path(p.parent, new_file_name + ext))

更简单地展示它的简单性:

Python 3.6 +:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))

Python 3.6以下的版本使用字符串格式方法:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))