Python: os重命名文件时如何保留文件扩展名?
Python: how to retain the file extension when renaming files with os?
假设我有一个包含 n csv
个文件的文件夹,我想重命名这些文件。新文件名将类似于 ABxxxx
,其中 xxxx
是从 1 到 1000 的递增数字。
在执行此操作时,如何保留原始文件扩展名 csv
?
到目前为止,我所做的只是更改了文件名,但删除了扩展名:
directory=r'C:\Me\MyDir'
subdir=[x[0] for x in os.walk(directory)]
subdir.pop(0)
for i in subdir:
temp_dir=r''+i
os.chdir(temp_dir)
a='A'
b='B'
for file in glob.glob("*.csv"):
for i in range(1,1001):
newname=a+b+i
os.rename(file,newname)
您只需将 '.csv'
附加到您的新文件名即可:
os.rename(file, newname + '.csv')
通常(对于任何文件类型),更好的方法是先使用 os.path.splitext
获取现有扩展名,然后将其附加到新文件名。
oldext = os.path.splitext(file)[1]
os.rename(file, newname + oldext)
使用 os.path.splitext
构建 (basepath, extension)
的元组,使用 enumerate
生成您的 "uniquifier"。现在您可以使用原始字符串格式将其粘合在一起
for i in subdir:
temp_dir=r''+i
os.chdir(temp_dir)
a='A'
b='B'
for idx, file in enumerate(glob.glob("*.csv")):
os.rename(file,'{0}{2}{1}'.format(*(os.path.splitext(file) + (idx,))))
假设我有一个包含 n csv
个文件的文件夹,我想重命名这些文件。新文件名将类似于 ABxxxx
,其中 xxxx
是从 1 到 1000 的递增数字。
在执行此操作时,如何保留原始文件扩展名 csv
?
到目前为止,我所做的只是更改了文件名,但删除了扩展名:
directory=r'C:\Me\MyDir'
subdir=[x[0] for x in os.walk(directory)]
subdir.pop(0)
for i in subdir:
temp_dir=r''+i
os.chdir(temp_dir)
a='A'
b='B'
for file in glob.glob("*.csv"):
for i in range(1,1001):
newname=a+b+i
os.rename(file,newname)
您只需将 '.csv'
附加到您的新文件名即可:
os.rename(file, newname + '.csv')
通常(对于任何文件类型),更好的方法是先使用 os.path.splitext
获取现有扩展名,然后将其附加到新文件名。
oldext = os.path.splitext(file)[1]
os.rename(file, newname + oldext)
使用 os.path.splitext
构建 (basepath, extension)
的元组,使用 enumerate
生成您的 "uniquifier"。现在您可以使用原始字符串格式将其粘合在一起
for i in subdir:
temp_dir=r''+i
os.chdir(temp_dir)
a='A'
b='B'
for idx, file in enumerate(glob.glob("*.csv")):
os.rename(file,'{0}{2}{1}'.format(*(os.path.splitext(file) + (idx,))))