我想把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)

其他回答

从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 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')

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

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

假设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')