遇到问题 在处理数据的时候想把.tif全部转化成.jpg后缀。
import os
files = os.listdir("images")
for filename in files:
portion = os.path.splitext(filename)
if portion[1] == ".tif":
newname = portion[0] + ".jpg"
os.rename(filename, newname)
代码涉及到文件目录 为了便于理解我们分部打印一下运行结果,首先看一下我所遍历的images文件的目录。  代码详细讲解
portion = os.path.splitext(filename)
print(portion)
os.path.splitext(filename)这个方法将文件名拆成名称和后缀并存放到一个元组中,我们打印来看运行出来的结果。  这里portion就是一个元组的形式,portion[0]得到的是文件的名称,portion[1]得到的是文件的后缀名。
if portion[1] == ".tif":
newname = portion[0] + ".jpg"
print(newname)
这里的判断形式,如果portion[1]也就是后缀为‘.tif’,我们取出名称和新的后缀连接。我们打印出来看一下。 
|