使用shutil移動重復文件出錯處理.思路:將重名的文件,重新命名到目標文件夾
import os
import platform
import re
import shutil
def move_file(soure_file_abspath, dirname):
'''移動文件,例:xxx(6).txt
soure_file_abspath:源文件絕對路徑
dirname : 目標文件夾或者目標文件絕對路徑
'''
file_suffix = '.txt'
# 判斷系統
if platform.system().find('Windows') != -1:
re_str = '\\'
else:
re_str = '/'
try:
# 處理傳入文件或者文件夾
assert os.path.isfile(dirname) or os.path.isdir(dirname), '請填寫正確路徑'
if os.path.isfile(dirname):
dirname, file_name = os.path.split(dirname)
elif os.path.isdir(dirname):
file_name = soure_file_abspath.split(re_str)[-1]
else:
file_name = soure_file_abspath.split(re_str)[-1]
# 當文件夾不存在是創建文件夾
if not os.path.exists(dirname):
os.makedirs(dirname, exist_ok=True)
assert os.path.exists(soure_file_abspath) or os.path.isfile(soure_file_abspath), '源文件不存在或不是文件'
# 文件移動
if not os.path.exists(os.path.join(dirname, file_name)):
shutil.move(soure_file_abspath, dirname)
return
ref1 = [x for x in os.listdir(dirname) if x.find(file_name.replace('%s' % file_suffix, ''))!=-1]
# 正則用於,自定義文件名
ref_out = [int(re.findall('\((\d+)\)%s' % file_suffix, x)[0]) for x in ref1 if
re.findall('\((\d+)\)%s' % file_suffix, x)]
# 當文件名重復時處理
if not ref_out:
new_file_abspath = os.path.join(dirname, ('(1)%s' % file_suffix).join(
file_name.split('%s' % file_suffix)))
else:
new_file_abspath = os.path.join(dirname, ('(%s)%s' % ((max(ref_out) + 1), file_suffix)).join(
file_name.split('%s' % file_suffix)))
shutil.move(soure_file_abspath, new_file_abspath)
except Exception as e:
print('err', e)
if __name__ == '__main__':
move_file(r'E:\work_file\test_data\Go_Python_000268.txt', r'E:\work_file\no_data')
with式移動,相當於先刪除了目標文件。
def move_with_file(soure_file_abspath, dstfile):
'''
with 移動文件,不考慮編碼問題,簡單暴力。
:param soure_file_abspath: 源文件絕對路徑
:param dstfile: 目標文件絕對路徑
'''
try:
with open(soure_file_abspath,'r') as f:
content = f.read()
with open(dstfile,'w') as f:
f.write(content)
os.remove(soure_file_abspath)
except Exception as e:
print('err',e)
if __name__ == '__main__':
move_with_file(r'E:\work_file\test_data\Go_Python_000268.txt', r'E:\work_file\no_data\Go_Python_000268.txt')