[英]with python: Find files and copy to another directory
目录树如下所示: https : //i.stack.imgur.com/nS9Vx.png
我的目标是输入成员 ID,程序应该分析所有天的相关文件 (activities.json) 并将所有这些文件复制到一个新目录中。 我还想重命名复制的文件 (1,2,3,4 .....),但出现错误。
通常我不应该收到错误,因为复制的文件会有不同的名称( 1 、 2 、 3 、 4 、 5 ......)
代码:
import os
import json
import win32com.client as win32 # pip install pywin32
import shutil
rootDir = 'C:/Users/Adam/Desktop/Linkedin/linkedin_hb_ma'
x = 1
for dirName, subdirList, fileList in os.walk(rootDir):
if dirName.endswith("1eb95ebb-d87d-Xd7-8c84-Xc"):
for file in fileList:
abs_path = os.path.join(dirName, file)
if file.endswith("activities.json"):
print('Found directory:'+ abs_path)
src = abs_path
dst = 'C:/Users/Adam/Desktop/Linkedin analyze/tableau bsp/1/3'
shutil.copy(src, dst)
m = str(x)
print(m)
os.rename('C:/Users/A.Abboudi/Desktop/Linkedin analyze/tableau bsp/1/3/activities.json', m)
x =x+ 1
错误:
---------------------------------------------------------------------------
FileExistsError Traceback (most recent call last)
<ipython-input-61-5491807f76ee> in <module>
20 m = str(x)
21 print(m)
---> 22 os.rename(abs_path, m)
23 x += 1
"FileExistsError: [WinError 183] Cannot create a file when that file already exists"
非常感谢
你已经检查过文件夹了吗? 它是否已经更改了您的文件名一次? 尝试删除 dest 文件夹中任何创建的文件!
如果不是这样,那么试试这个:
代码
if not os.path.exists("name of folder/file"):
os.rename('C:/Users/A.Abboudi/Desktop/Linkedin analyze/tableau bsp/1/3/activities.json', m)
不要试图从这里复制,因为我不确定这个标识!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.