FileNotFoundError: [Errno 2] No such file or directory (even though it gives the name of the exact file in the directory)

FileNotFoundError: [Errno 2] No such file or directory (even though it gives the name of the exact file in the directory)

注意:我在发帖前检查了所有其他位置是否存在类似问题。此问题在 48 小时前不存在,并且没有任何更改。

我的问题是我正在将 PDF 转换为 TXT,因此我可以获取信息并将其放入数据库。第一个脚本是转换:

import PyPDF2
import os
import time

#Scan Directory

directory = 'C:\Users\Username\OneDrive\Desktop\python'
for file in os.listdir(directory):
    if not file.endswith(".pdf"): #Skip non-PDF files
        continue
    with open(os.path.join(directory,file), 'rb') as pdfFileObj:  # Changes here
        pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
        pageObj = pdfReader.getPage(0)
        text=pageObj.extractText()
        print("Writing File "+ file +" to TXT.")
        file2=open(r"C:\Users\Username\OneDrive\Desktop\python\"+file.replace('pdf','txt'),"a") #Write as TXT files
        file2.writelines(text)
        print("Done saving.")
        file2.close()

那部分仍然可以正常工作。它需要 3132019_4102019_1617.pdf 并将其转换为 3132019_4102019_1617.txt。 (这最终将被用来获取大约 200 多个 pdf 并隐藏它们)。第二部分,现在有问题的部分,说明该文件不存在。唯一的问题是,为了让它告诉我文件名不存在,文件本身必须存在。

第二个脚本(部分):

import os
import time
#import sys
import mysql.connector
from collections import deque
from itertools import groupby


directory = 'C:\Users\Username\OneDrive\Desktop\python'
for file in os.listdir(directory):
    if file.endswith(".txt"): #Skip non-TXT files
        with open(file, 'r') as f:
            nameList = [line.strip() for line in f]
            transferlist = nameList
            char_list=['UPS A','PDU A1','PDU B1','CRAC 03','PDU A2','CRAC 05','UPS B',
            'PDU B2','CRAC 06','CRAC 07','PDU A4','DC CNC','ATS 1','ATS 2','CRAC 02','CRAC 04','CRAC 01',
            'CRAC 09','CRAC 08','CRAC 10','CRAC 11','ATS','DC A1','DC B1','PDU A4''a','b','c','d','e',
            'f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
            'w','x','y','z','/',':']
            transferlist2=[ele for ele in transferlist if all(ch not in ele for ch in char_list)]

  File "c:\Users\Username\OneDrive\Desktop\python\CLT4_SQL_Insert_3132019_4102019_1617.py", line 12, in <module>
    with open(file, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: '3132019_4102019_1617.txt'

如果我删除 .txt 文件,那么脚本会运行并关闭,什么都不做,没有错误。我从不调用要查找的 .txt 文件,因为它们会很多,而且应该完成所有这些。它特别可以获取 .txt 文件的名称这一事实意味着它确实存在,这与它所说的不同。它在 48 小时前完美运行,所有内容都位于完全相同的文件夹中。

而不是

open(file, 'r')

你可能想要

open(os.path.join(directory, file), "r")