我已经让我们说了5个目录,让他们称之为dir1,dir2,dir3,dir4,dir5。
这些都在当前目录中。每个文件都包含1个名为title.mkv的文件。我想将文件重命名为它们所在的目录名,即dir1中的文件title.mkv,我想重命名为dir1.mkv。
我还想将文件移动到另一个文件夹。除了os和glob之外,我还需要哪些python工具?
答案 0 :(得分:0)
如果您有完整的文件名和目录,要重命名文件,可以使用
import os
f_name = 'E:/temp/nuke.mkv'
# Removes '/' at the end of string
while f_name.endswith('/'):
f_name = f_name[:-1]
# Generates List Containing Directories and File Name
f_name_split = f_name.split('/')
f_path = ''
# Iterates Through f_name_split, adding directories to new_f_path
for i in range(len(f_name_split)-1):
f_path += f_name_split[i] + '/'
# Makes New Name Based On Folder Name
new_name = f_name_split[-2] + '.mkv'
# Gets The Old File Name
f_name = f_name_split[-1]
# Renames The File
os.rename(f_path + f_name, f_path + new_name)
要遍历所有目录,您可以递归执行,让系统将其输出到文件[windows:dir / s / b / a> file.txt],或者使用os.walk。要移动文件,可以使用os.rename(源,目标)
答案 1 :(得分:0)
以下内容应该可行,但如果每个源文件夹有多个文件,则会出现问题:
import os
source_folder = r"c:\my_source_folder"
target_folder = r"c:\target_folder"
for directory_path, dirs, files in os.walk(source_folder):
# Current directory name
directory = os.path.split(directory_path)[1]
# Ensure only MKV files are processed
files = [file for file in files if os.path.splitext(file)[1].lower() == '.mkv']
# Rename each file
for file in files:
source = os.path.join(directory_path, file)
target = os.path.join(target_folder, directory + ".mkv")
try:
os.rename(source, target)
except OSError:
print "Failed to rename: {} to {}".format(source, target)
它将搜索源文件夹中的所有子文件夹,并使用当前文件夹名称作为目标名称。
答案 2 :(得分:0)
以下函数使用shutil.move
,它跨文件系统移动,并在目标文件存在时具有覆盖保护。文件名可以是相对的。
from os.path import basename, dirname, isfile, abspath, splitext
from shutil import move
def rename_to_dirname_and_move(name, dst, overwrite=False, verbose=False):
"""renames 'name' to its directory name, keeping its extension
intact and moves to 'dst' directory across filesystem
"""
if not isfile(name):
raise ValueError("{} is not a file or doesn't exist".format(name))
abs_name = abspath(name)
dir_name = basename(dirname(abs_name))
new_name = '{}{}'.format(dir_name, splitext(name)[1])
dst_name = os.path.join(dst, new_name)
if not overwrite and isfile(dst_name):
raise OSError('file {} exists'.format(dst_name))
try:
move(abs_name, dst_name)
except Exception as e:
print("Can't move {} to {}, error: {}".format(abs_name, dst_name,e))
else:
if verbose:
print('Moved {} to {}'.format(abs_name, dst_name))