我有一个用于将所有jpg文件从源移动到目标的代码。第一次代码运行正常,它移动了文件,但是如果我再次运行它,则会出现一个错误,表明该文件已存在。
Traceback (most recent call last):
File "/Users/tom/Downloads/direc.py", line 16, in <module>
shutil.move(jpg, dst_pics)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 542, in move
raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path '/Users/tom/Downloads/Dest/Pictures/Photo3.jpg' already exists
Run Code Online (Sandbox Code Playgroud)
这是我的代码
import os
import glob
import shutil
local_src = '/Users/tom/Downloads/'
destination = 'Dest'
src = local_src + destination
dst_pics = src + '/Pictures/'
print(dst_pics)
for pic in glob.iglob(os.path.join(src, "*.jpg")):
if os.path.isfile(pic):
if not (os.path.isfile(dst_pics + pic)):
shutil.move(pic, dst_pics)
else:
print("File exists")
Run Code Online (Sandbox Code Playgroud)
我有什么办法可以覆盖文件或检查文件是否存在并跳过它?
我能够通过遵循@Justas G解决方案来解决。
这是解决方案
for …Run Code Online (Sandbox Code Playgroud) 我正在尝试从文本文件中读取第一列和第三列,并将它们添加在一起。
下面的代码可以完美地工作,并为我提供所需的结果,但是尝试找出是否有更好的pythonic方式编写此代码?
with open('random.txt', 'r') as fn:
next(fn)
numbers = fn.readlines()
first_col = [int(x.split(',')[0]) for x in numbers]
third_col = [int(y.split(',')[2]) for y in numbers]
result = [v + z for v, z in zip(first_col, third_col)]
print(result)
Run Code Online (Sandbox Code Playgroud)
随机文件实际上是一个随机文件。
col1,col2,col3
44,65,78
55,87,98
12,32,62
Run Code Online (Sandbox Code Playgroud)
结果:
[122, 153, 74]
Run Code Online (Sandbox Code Playgroud) python ×2