Python接受不存在的文件

2024-06-26 14:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

经过多次修改后,这个错误仍然困扰着我。我有一个任务,其中一部分是通过输入计算机上现有文件的文件名来读取,直到用户输入一个不存在的文件名。我的程序的这一部分如下所示:

import os.path
file_lst=[]
f=True  

while f:
    tx=input("Unesite file path:")
    if os.path.isfile(tx):
        file_lst.append(tx)

    else:
        print("Broken.")
        f=False

print(file_lst)

print("Broken.")语句用于检查循环是否实际中断this:It accepts 第一个输入是一个现有的文件,然后我输入一个不存在的文件,之后循环中断,file_lst被打印出来,然后,程序再次请求文件输入(在代码的其余部分中不存在)。当我输入一个不存在的文件时,程序停止并打印出FileNotFoundError(错误位于我打开文件的文件的后面)。错误屏幕如下所示:

Unesite file path:\\vmware-host\Shared Folders\Desktop\primer.txt
Unesite file path:f
Broken.
['\\\\vmware-host\\Shared Folders\\Desktop\\primer.txt']
Unesite file path:g
Traceback (most recent call last):
File "//vmware-host/Shared Folders/Desktop/VDZ_3.py", line 25, in  <module>
f=open(tx,"r")
FileNotFoundError: [Errno 2] No such file or directory: 'g'

以下是发生FileNotFoundError的地方:

if len(file_lst)==0:
    print("Nema unetih imena fajlova.")
else:
    for tx in file_lst:
        tx=input("Unesite file path:")
        f=open(tx,"r")        

我找不到一个合理的解释,所以我写了这篇文章,希望能有所启发


Tags: 文件path程序host错误foldersfilevmware