我试图用Python重命名目录中的一些文件。
假设我有一个名为CHEESE_CHEESE_TYPE的文件。***,并希望删除CHEESE_,因此我的结果文件名将是CHEESE_TYPE
我正在尝试使用os.path.split,但它不能正常工作。我也考虑过使用字符串操作,但也没有成功。
我试图用Python重命名目录中的一些文件。
假设我有一个名为CHEESE_CHEESE_TYPE的文件。***,并希望删除CHEESE_,因此我的结果文件名将是CHEESE_TYPE
我正在尝试使用os.path.split,但它不能正常工作。我也考虑过使用字符串操作,但也没有成功。
当前回答
进口操作系统 进口的字符串 def rename_files ():
#List all files in the directory
file_list = os.listdir("/Users/tedfuller/Desktop/prank/")
print(file_list)
#Change current working directory and print out it's location
working_location = os.chdir("/Users/tedfuller/Desktop/prank/")
working_location = os.getcwd()
print(working_location)
#Rename all the files in that directory
for file_name in file_list:
os.rename(file_name, file_name.translate(str.maketrans("","",string.digits)))
rename_files ()
其他回答
假设您已经在目录中,并且注释中的“前8个字符”始终为真。(虽然“CHEESE_”是7个字符…? 如果是,将下面的8改为7)
from glob import glob
from os import rename
for fname in glob('*.prj'):
rename(fname, fname[8:])
这类东西非常适合IPython,它具有shell集成。
In [1] files = !ls
In [2] for f in files:
newname = process_filename(f)
mv $f $newname
注意:要将它存储在脚本中,请使用.ipy扩展名,并在所有shell命令前加上!
参见:http://ipython.org/ipython-doc/stable/interactive/shell.html
这对我很有用。
import os
for afile in os.listdir('.'):
filename, file_extension = os.path.splitext(afile)
if not file_extension == '.xyz':
os.rename(afile, filename + '.abc')
那么这个呢:
import re
p = re.compile(r'_')
p.split(filename, 1) #where filename is CHEESE_CHEESE_TYPE.***
试试这个:
import os
import shutil
for file in os.listdir(dirpath):
newfile = os.path.join(dirpath, file.split("_",1)[1])
shutil.move(os.path.join(dirpath,file),newfile)
我假设您不想删除文件扩展名,但您可以对句号进行相同的分割。