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


当前回答

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

其他回答

使用os.rename:

import os

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

用法:

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

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

import pathlib

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

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

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

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

下面是一个只使用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)