英文:
Error while copying files in Python from one folder to another
问题
我想根据PDF中的文本复制我的收据。复制功能不起作用,并显示以下错误。 FileNotFoundError: [Errno 2] No such file or directory
尽管它打印出文件列表,文件确实存在。
************************** 代码 ************************
#//设置路径
ls_base = r"D:\OneDrive\Documents\Receipts"
ls_t1 = r"D:\OneDrive\Documents\Receipts\Org1"
ls_t2 = r"D:\OneDrive\Documents\Receipts\Org2"
os.chdir(ls_base)
files = os.listdir(ls_base)
print(files) #正确打印文件列表
os.chdir(ls_base)
for files in os.listdir(ls_base):
if files.endswith(".pdf"):
pdfFileObj = open(files, 'rb')
pdfReader = PyPDF2.PdfReader(pdfFileObj)
pageObj = pdfReader.pages[0]
ls_name = re.findall('The Paint Shop', pageObj.extract_text())
pdfFileObj.close()
ls_file = ls_base + files //获取完整文件名
if ls_name:
print(ls_name, pageObj.extract_text().split('Items')[1].split('\n')[1], files)
ls_target = ls_t1 + files
shutil.copy2(ls_file, ls_target)
else:
#//将文件复制到位置"D:\OneDrive\Documents\Receipt\Org2"
ls_target = ls_t2 + files
shutil.copy2(ls_file, ls_target)
英文:
I want to copy my receipts based on the text in PDF. The copy function doesn't work and gives the following error. FileNotFoundError: [Errno 2] No such file or directory
Though it prints the list of files and it is there.
************************** CODE ************************
#//set path
ls_base = r"D:\OneDrive\Documents\Receipts"
ls_t1 = r"D:\OneDrive\Documents\Receipts\Org1"
ls_t2 = r"D:\OneDrive\Documents\Receipts\Org2"
os.chdir(ls_base)
files = os.listdir(ls_base)
print(files) #PRINTS THE LIST OF FILES CORRECTLY
os.chdir(ls_base)
for files in os.listdir(ls_base):
if files.endswith(".pdf"):
pdfFileObj = open(files, 'rb')
pdfReader = PyPDF2.PdfReader(pdfFileObj)
pageObj = pdfReader.pages[0]
ls_name = re.findall(r'The Paint Shop', pageObj.extract_text())
pdfFileObj.close()
ls_file = ls_base + files //get complete file name
if ls_name:
print(ls_name, pageObj.extract_text().split('Items')[1].split('\n')[1], files)
ls_target = ls_t1 + files
shutil.copy2(ls_file, ls_target)
else:
#//copy the file to the location "D:\OneDrive\Documents\Receipt\Org2"
ls_target = ls_t2 + files
shutil.copy2(ls_file, ls_target)
答案1
得分: 1
我认为在这一行中 ls_base
和 files
之间缺少了 /
:
ls_file = ls_base + files //获取完整的文件名
所以 ls_file
最终等于 "D:\OneDrive\Documents\ReceiptsYOUR_PDF.pdf"
通常打印出这些名称会有所帮助,以查看是否得到了预期的结果。
英文:
I think there's "/" missing between ls_base
and files
in this line:
ls_file = ls_base + files //get complete file name
So ls_file ends up being equal to "D:\OneDrive\Documents\ReceiptsYOUR_PDF.pdf"
In general it helps to print out the names to see if you're getting what is expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论