安全复制文件 python 程序 - 代码有什么问题
safe copy file python program - what's problem in code
我正在尝试将文件从一个目标复制到另一个目标,我按照这个程序操作,但我不知道我做错了什么,但文件没有复制到目标文件夹。
https://gist.github.com/alexwlchan/c2adbb8ee782f460e5ec
我不太了解编程,我只是按照教程。
我在此代码中添加了额外内容
src = ("F:\Work\")
dst = ("F:\ws\")
所以,如果我错了,请纠正我。
提前致谢!
import filecmp
import os
import shutil
src = ("F:\Work\")
dst = ("F:\ws\")
def _increment_filename(filename, marker='-'):
basename, fileext = os.path.splitext(filename)
if marker not in basename:
base = basename
value = 0
else:
base, counter = basename.rsplit(marker, 1)
try:
value = int(counter)
except ValueError:
base = basename
value = 0
while True:
if value == 0:
value += 1
yield filename
value += 1
yield '%s%s%d%s' % (base, marker, value, fileext)
def copyfile(src, dst):
if not os.path.exists(src):
raise ValueError('Source file does not exist: {}'.format(src))
if not os.path.exists(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
while True:
dst_gen = _increment_filename(dst)
dst = next(dst_gen)
if os.path.exists(dst):
if filecmp.cmp(src, dst):
return dst
else:
try:
src_fd = os.open(src, os.O_RDONLY)
dst_fd = os.open(dst, os.O_WRONLY|os.O_EXCL|os.O_CREAT|os.O_EXLOCK)
# Read 100 bytes at a time, and copy them from src to dst
while True:
data = os.read(src_fd, 100)
os.write(dst_fd, data)
# When there are no more bytes to read from the source
# file, 'data' will be an empty string
if not data:
break
# If we get to this point, then the write has succeeded
return dst
except OSError as e:
if e.errno != 17 or e.strerror != 'File exists':
raise
else:
print('Race condition: %s just popped into existence' % dst)
finally:
os.close(src_fd)
os.close(dst_fd)
# Copying to this destination path has been unsuccessful, so increment
# the path and try again
dst = next(dst_gen)
def move(src, dst):
dst = copyfile(src, dst)
os.remove(src)
return dst
程序没有错误,程序运行很好,但目标文件夹是空白的。
预期结果应该是将文件复制到目标文件夹并且低于程序的预期结果
如果一个文件已经存在于dst,它不会被覆盖,但是:
* If it is the same as the source file, do nothing
* If it is different to the source file, pick a new name for the copy that
is distinct and unused, then copy the file there.
抱歉,该代码似乎过于复杂了。这几乎适用于所有情况。如果 dst 已经存在,它将在目录名称中添加下划线 ( _ ),直到找到未使用的下划线:
import os
import shutil
import filecmp
src = ("D:\Documents\oof")
dst = ("D:\oof")
validextensions = ["jpeg", "txt", "pdf", "pptx"]
def copydir(src, dst):
if not os.path.isdir(src):
print("Source directory doesn't exist.")
return None
if not os.path.exists(dst):
os.mkdir(dst)
elif not os.path.isdir(dst):
while not os.path.isdir(dst):
dst += "_"
os.mkdir(dst)
for file in os.listdir(src):
frompath = os.path.join(src, file)
topath = os.path.join(dst, file)
if os.path.isfile(frompath):
complete = False
if not any([file[-1 * len(ext):] == ext for ext in validextensions]):
complete = True
while not complete:
if os.path.isfile(topath):
if filecmp.cmp(frompath, topath):
complete = True
else:
topath = topath[:topath.index(".")] + "_" + topath[topath.index("."):]
else:
shutil.copyfile(frompath, topath)
complete = True
elif os.path.isdir(frompath):
copydir(frompath, topath)
copydir(src, dst)
随着 OP 列出了他们想要的更多功能,我很喜欢它变得越来越复杂 facepalm
我正在尝试将文件从一个目标复制到另一个目标,我按照这个程序操作,但我不知道我做错了什么,但文件没有复制到目标文件夹。 https://gist.github.com/alexwlchan/c2adbb8ee782f460e5ec
我不太了解编程,我只是按照教程。
我在此代码中添加了额外内容
src = ("F:\Work\")
dst = ("F:\ws\")
所以,如果我错了,请纠正我。
提前致谢!
import filecmp
import os
import shutil
src = ("F:\Work\")
dst = ("F:\ws\")
def _increment_filename(filename, marker='-'):
basename, fileext = os.path.splitext(filename)
if marker not in basename:
base = basename
value = 0
else:
base, counter = basename.rsplit(marker, 1)
try:
value = int(counter)
except ValueError:
base = basename
value = 0
while True:
if value == 0:
value += 1
yield filename
value += 1
yield '%s%s%d%s' % (base, marker, value, fileext)
def copyfile(src, dst):
if not os.path.exists(src):
raise ValueError('Source file does not exist: {}'.format(src))
if not os.path.exists(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
while True:
dst_gen = _increment_filename(dst)
dst = next(dst_gen)
if os.path.exists(dst):
if filecmp.cmp(src, dst):
return dst
else:
try:
src_fd = os.open(src, os.O_RDONLY)
dst_fd = os.open(dst, os.O_WRONLY|os.O_EXCL|os.O_CREAT|os.O_EXLOCK)
# Read 100 bytes at a time, and copy them from src to dst
while True:
data = os.read(src_fd, 100)
os.write(dst_fd, data)
# When there are no more bytes to read from the source
# file, 'data' will be an empty string
if not data:
break
# If we get to this point, then the write has succeeded
return dst
except OSError as e:
if e.errno != 17 or e.strerror != 'File exists':
raise
else:
print('Race condition: %s just popped into existence' % dst)
finally:
os.close(src_fd)
os.close(dst_fd)
# Copying to this destination path has been unsuccessful, so increment
# the path and try again
dst = next(dst_gen)
def move(src, dst):
dst = copyfile(src, dst)
os.remove(src)
return dst
程序没有错误,程序运行很好,但目标文件夹是空白的。
预期结果应该是将文件复制到目标文件夹并且低于程序的预期结果
如果一个文件已经存在于dst,它不会被覆盖,但是:
* If it is the same as the source file, do nothing
* If it is different to the source file, pick a new name for the copy that
is distinct and unused, then copy the file there.
抱歉,该代码似乎过于复杂了。这几乎适用于所有情况。如果 dst 已经存在,它将在目录名称中添加下划线 ( _ ),直到找到未使用的下划线:
import os
import shutil
import filecmp
src = ("D:\Documents\oof")
dst = ("D:\oof")
validextensions = ["jpeg", "txt", "pdf", "pptx"]
def copydir(src, dst):
if not os.path.isdir(src):
print("Source directory doesn't exist.")
return None
if not os.path.exists(dst):
os.mkdir(dst)
elif not os.path.isdir(dst):
while not os.path.isdir(dst):
dst += "_"
os.mkdir(dst)
for file in os.listdir(src):
frompath = os.path.join(src, file)
topath = os.path.join(dst, file)
if os.path.isfile(frompath):
complete = False
if not any([file[-1 * len(ext):] == ext for ext in validextensions]):
complete = True
while not complete:
if os.path.isfile(topath):
if filecmp.cmp(frompath, topath):
complete = True
else:
topath = topath[:topath.index(".")] + "_" + topath[topath.index("."):]
else:
shutil.copyfile(frompath, topath)
complete = True
elif os.path.isdir(frompath):
copydir(frompath, topath)
copydir(src, dst)
随着 OP 列出了他们想要的更多功能,我很喜欢它变得越来越复杂 facepalm