我想把a.txt改为b.kml。
当前回答
操作系统。重命名(旧的,新的)
这可以在Python文档中找到:http://docs.python.org/library/os.html
其他回答
如果你正在使用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!!")
使用Pathlib库的路径。用Rename代替os.rename:
import pathlib
original_path = pathlib.Path('a.txt')
new_path = original_path.rename('b.kml')
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 +
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.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))