这个问题在这里已有答案:
我试图擦除除最后4个之外的所有索引(字符)和python中的文件扩展名。例如:a2b-0001.tif到0001.tif a3tcd-0002.tif到0002.tif as54d-0003.tif到0003.tif
让我们说包含那些tifs文件的文件夹“a”,“b”和“c”位于D:\ photos中
那是我到目前为止的地方:
import os
os.chdir('C:/photos')
for dirpath, dirnames, filenames in os.walk('C:/photos'):
os.rename (filenames, filenames[-8:])
为什么那'不工作?
只要你有Python 3.4+,pathlib
就会让它非常简单:
import pathlib
def rename_files(path):
## Iterate through children of the given path
for child in path.iterdir():
## If the child is a file
if child.is_file():
## .stem is the filename (minus the extension)
## .suffix is the extension
name,ext = child.stem, child.suffix
## Rename file by taking only the last 4 digits of the name
child.rename(name[-4:]+ext)
directory = pathlib.Path(r"C:\photos").resolve()
## Iterate through your initial folder
for child in directory.iterdir():
## If the child is a folder
if child.is_dir():
## Rename all files within that folder
rename_files(child)
请注意,因为您正在截断文件名,可能会发生冲突,导致文件被覆盖(即名为12345.jpg
和22345.jpg
的文件都将重命名为2345.jpg
,第二次覆盖第一个文件)。