在我的python脚本中,我将一堆文件从不同的子目录移动到一个位置,这样做的问题是有多个文件是相同的。
我当前运行的代码是:
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.endswith('.log'):
shutil.move(os.path.join(root, file), FILE_LOCATION_PATH)这样做的问题是它最终会抛出以下错误:
File "downloader.py", line 78, in <module>
shutil.move(os.path.join(root, file), FILE_LOCATION_PATH)
File "/usr/lib/python3.6/shutil.py", line 548, in move
raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path '/home/a.log' already exists我可以通过将我的移动行更改为copy来取消这一点,如下所示
shutil.move(os.path.join(root, file), FILE_LOCATION_PATH)但是,这将用最新的副本替换任何具有此名称的文件。我正在尝试找出一种方法来重命名任何同名的文件,以遵循如下的命名约定
a.log
a_1.log
a_2.log
任何关于如何最好地处理这一点或示例代码的建议。我是Python的新手,正在尝试完成我的第一个实用脚本。
发布于 2020-01-30 01:53:21
如果你对像filename.log, filename.log_1 ...这样的文件名没意见,那么代码就比你的原始代码多了4行:
import shutil
import os
FILE_LOCATION_PATH='/destination/directory'
dir_path='/source/directory'
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.endswith('.log'):
count = 1
destination_file = os.path.join(FILE_LOCATION_PATH, file)
while os.path.exists(destination_file):
destination_file = os.path.join(FILE_LOCATION_PATH, f"{file}_{count}")
count += 1
shutil.move(os.path.join(root, file), destination_file)发布于 2020-01-30 00:02:07
也许这就是你所需要的
import re
import os
import shutil
FILE_LOCATION_PATH = 'dst'
def increment_file_name(f_name):
"""
a.txt -> a_1.txt
a_1.txt -> a_2.txt
"""
def split_f_name(f_name):
m = re.match(r"^(.+?)(_(\d+))?(\.(.+))??$", f_name)
return m.group(1), int(m.group(3) or 0), m.group(5)
def join_f_name(name, suffix, ext):
if not ext:
return "{}_{}".format(name, suffix)
return "{}_{}.{}".format(name, suffix, ext)
dirname = os.path.dirname(f_name)
name, suffix, ext = split_f_name(os.path.basename(f_name))
if dirname:
return os.path.join(dirname, join_f_name(name, suffix + 1, ext))
else:
return join_f_name(name, suffix + 1, ext)
def safe_move(path):
dir, f_name = os.path.split(path)
while os.path.exists(os.path.join(FILE_LOCATION_PATH, f_name)):
f_name = increment_file_name(f_name)
shutil.move(path, os.path.join(FILE_LOCATION_PATH, f_name))
for root, dirs, files in os.walk('src'):
for file in files:
if file.endswith('.log'):
safe_move(os.path.join(root, file))https://stackoverflow.com/questions/59968879
复制相似问题