确定文件是否存在

2024-04-26 13:34:05 发布

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

作为python3.7.2中错误处理过程的一部分,我试图确定文件是否存在。作为过程的一部分,我尝试使用os.path.isfile()但是,if语句似乎出现了语法错误。你知道吗

我该如何着手解决这个问题,使其正确阅读?你知道吗

代码是:

import sys
import os
import random
import time

while True:
    try:
        user_input = input("Enter the path of your file (Remember to include the file name and extension): ")   # Imports user defined file

    if os.path.isfile(user_input) == False:
        print("I did not find the file at, "+str(user_input)                                                    # Checks if file is present
        continue

    else:
        break

编辑:包含错误类型


Tags: 文件thepath代码importinputifos
3条回答
import os
from builtins import input

while True:
    user_input = input(
        "Enter the path of your file (Remember to include the file name and extension): ")

    if not os.path.isfile(user_input):
        print(f"I did not find the file at {user_input}")
        continue
    else:
        break

最简单的,因为我不知道你为什么需要一个try语句:

import os

path = input("Enter the path of your file (Remember to include the file "
             "name and extension)")
if os.path.exists():
    pass
else:
    print("I did not find the file at, "+str(path))

试试这个

import sys
import os
import random
import time

while True:
    try:
        user_input = input("Enter the path of your file (Remember to include the file name and extension): ")   # Imports user defined file

        if os.path.isfile(user_input):
            print("I did not find the file at, "+str(user_input))                                                # Checks if file is present
            continue
        else:
            break
    except:
        print('Error')

然而,这许多代码是不需要的。。。 这就足够了

import sys
import os
import random
import time
while True:
    user_input = input("Enter the path of your file (Remember to include the file name and extension): ")   # Imports user defined file
    if not os.path.isfile(user_input):
        print("I did not find the file at, "+str(user_input))
        continue
    else:
        # some functions
        break

相关问题 更多 >