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


当前回答

从Python 3.3及更高版本开始,通常首选使用os。Replace而不是os。如果目标文件已经存在,则不会引发FileExistsError。

assert os.path.isfile('old.txt')
assert os.path.isfile('new.txt')

os.rename('old.txt', 'new.txt')
# Raises FileExistsError
os.replace('old.txt', 'new.txt')
# Does not raise exception

assert not os.path.isfile('old.txt')
assert os.path.isfile('new.txt')

请参见文档。

其他回答

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!!")

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

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

下面是一个只使用pathlib而不使用os的例子,它改变了目录中所有文件的名称,基于字符串替换操作,而不使用also字符串连接:

from pathlib import Path

path = Path('/talend/studio/plugins/org.talend.designer.components.bigdata_7.3.1.20200214_1052\components/tMongoDB44Connection')

for p in path.glob("tMongoDBConnection*"):
    new_name = p.name.replace("tMongoDBConnection", "tMongoDB44Connection")
    new_name = p.parent/new_name
    p.rename(new_name)
import shutil
import os

files = os.listdir("./pics/") 

for key in range(0, len(files)):
   print files[key]
   shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")

这个应该可以了。python 3 +