Python 将文件复制到新目录并在文件名已存在时重命名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18383384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python copy files to a new directory and rename if file name already exists
提问by GISKid
I've already read this threadbut when I implement it into my code it only works for a few iterations.
我已经阅读了这个线程,但是当我将它实现到我的代码中时,它只适用于几次迭代。
I'm using python to iterate through a directory (lets call it move directory) to copy mainly pdf files (matching a unique ID) to another directory (base directory) to the matching folder (with the corresponding unique ID). I started using shutil.copy
but if there are duplicates it overwrites the existing file.
我正在使用 python 遍历一个目录(我们称之为移动目录)以将主要 pdf 文件(匹配唯一 ID)复制到另一个目录(基本目录)到匹配文件夹(具有相应的唯一 ID)。我开始使用,shutil.copy
但如果有重复,它会覆盖现有文件。
I'd like to be able to search the corresponding folder to see if the file already exists, and iteratively name it if more than one occurs.
我希望能够搜索相应的文件夹以查看该文件是否已经存在,如果出现多个文件,则对其进行迭代命名。
e.g.
例如
- copy file 1234.pdf to folder in base directory 1234.
- if 1234.pdf exists to name it 1234_1.pdf,
- if another pdf is copied as 1234.pdf then it would be 1234_2.pdf.
- 将文件 1234.pdf 复制到基本目录 1234 中的文件夹。
- 如果存在 1234.pdf 将其命名为 1234_1.pdf,
- 如果另一个 pdf 被复制为 1234.pdf,那么它将是 1234_2.pdf。
Here is my code:
这是我的代码:
import arcpy
import os
import re
import sys
import traceback
import collections
import shutil
movdir = r"C:\Scans"
basedir = r"C:\Links"
try:
#Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
for filename in files:
#find the name location and name of files
path = os.path.join(root, filename)
print path
#file name and extension
ARN, extension = os.path.splitext(filename)
print ARN
#Location of the corresponding folder in the new directory
link = os.path.join(basedir,ARN)
# if the folder already exists in new directory
if os.path.exists(link):
#this is the file location in the new directory
file = os.path.join(basedir, ARN, ARN)
linkfn = os.path.join(basedir, ARN, filename)
if os.path.exists(linkfn):
i = 0
#if this file already exists in the folder
print "Path exists already"
while os.path.exists(file + "_" + str(i) + extension):
i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)
else:
shutil.copy(path, link)
print ARN + " " + "Copied"
else:
print ARN + " " + "Not Found"
采纳答案by Jblasco
Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.
有时重新开始会更容易......如果有任何错字,我很抱歉,我没有时间彻底测试它。
movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
for filename in files:
# I use absolute path, case you want to move several dirs.
old_name = os.path.join( os.path.abspath(root), filename )
# Separate base from extension
base, extension = os.path.splitext(filename)
# Initial new name
new_name = os.path.join(basedir, base, filename)
# If folder basedir/base does not exist... You don't want to create it?
if not os.path.exists(os.path.join(basedir, base)):
print os.path.join(basedir,base), "not found"
continue # Next filename
elif not os.path.exists(new_name): # folder exists, file does not
shutil.copy(old_name, new_name)
else: # folder exists, file exists as well
ii = 1
while True:
new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
if not os.path.exists(new_name):
shutil.copy(old_name, new_name)
print "Copied", old_name, "as", new_name
break
ii += 1
回答by Jblasco
I would say you have an indentation problem, at least as you wrote it here:
我会说你有一个缩进问题,至少在你在这里写的时候:
while not os.path.exists(file + "_" + str(i) + extension):
i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)
should be:
应该:
while os.path.exists(file + "_" + str(i) + extension):
i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)
Check this out, please!
看看这个,拜托!
回答by user8924811
I always use the time-stamp - so its not possible, that the file exists already:
我总是使用时间戳 - 所以不可能,文件已经存在:
import os
import shutil
import datetime
now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")
src_dir="C:\Users\Asus\Desktop\Versand Verwaltung\Versand.xlsx"
dst_dir="C:\Users\Asus\Desktop\Versand Verwaltung\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
回答by Alex Seceleanu
For me shutil.copy is the best:
对我来说 shutil.copy 是最好的:
import shutil
#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)
You can change the path of the files as you want.
您可以根据需要更改文件的路径。