Reputation: 471
Lets say you have the following df:
dfresult_secondlook = {'relfilepath': ['test.pdf', 'epic.pdf' ], 'col2': [3, 4]}
I want to move a file that is in this df to another folder with the following code:
#moving files from secondlook df to secondlook folder
sourceDir = 'C:\\Users\\Max12\\Desktop\\xml\\pdfminer\\UiPath\\attachments\\75090058\\Status\\PDFsend'
destDir = 'C:\\Users\\Max12\\Desktop\\xml\\pdfminer\\UiPath\\attachments\\75090058\\Status\\SecondLook'
files = os.listdir(sourceDir)
filesToMove = dfresult_secondlook
def move(file, sourceDir, destDir):
sourceFile = os.path.join(sourceDir, file)
if not os.path.exists(destDir):
os.makedirs(destDir)
try:
shutil.move(sourceFile, destDir)
except:
pass
for i in range(len(filesToMove)):
file = filesToMove['relfilepath'][i]
move(file,sourceDir,destDir)
#writing files to excel for further examination
book = load_workbook(r"C:\Users\Max12\Desktop\xml\pdfminer\UiPath\attachments\75090058\secondlook.xlsx")
writer = pd.ExcelWriter(r"C:\Users\Max12\Desktop\xml\pdfminer\UiPath\attachments\75090058\secondlook.xlsx", engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
dfresult_secondlook.to_excel(writer, "Main", header = False, index = False, startrow = writer.sheets['Main'].max_row)
writer.save()
However, I'm getting a KeyError:
KeyError: 0
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-13-4043ec85df9c> in <module>
17
18 for i in range(len(filesToMove)):
---> 19 file = filesToMove['relfilepath'][i]
20 move(file,sourceDir,destDir)
21
I don't see what's going wrong after 2 hours..
Please help!
Upvotes: 1
Views: 249
Reputation: 13488
According to the sample data you provided, relfilepath
is a dict which does not always have 0 as a key. Thus, your for / loop, starting from 0, fails.
You could then try this:
for i in range(len(filesToMove)):
try:
file = filesToMove['relfilepath'][i]
move(file,sourceDir,destDir)
except KeyError:
continue
PS: you should modify the beginning of your post, where dfresult_secondlook
shows 'relfilepath' as a list instead of a dict.
Upvotes: 1