python移动文件问题

使用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')
 
原文地址:https://www.cnblogs.com/banxiancode/p/15710932.html