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


当前回答

import os
import re
from pathlib import Path

for f in os.listdir(training_data_dir2):
  for file in os.listdir( training_data_dir2 + '/' + f):
    oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
    newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
    p=oldfile
    p.rename(newfile)

其他回答

下面是一个只使用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 os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)
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)

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

os.system('mv oldfile newfile')

如何修改目录中文件名的首字母。

import os
path = "/"

for file in os.listdir(path):
    os.rename(path + file, path + file.lower().capitalize())

then = os.listdir(path)
print(then)