判断文件是否存在

我正在尝试确定文件是否存在,作为 Python 3.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

编辑:包括错误类型


PIPIONE
浏览 185回答 3
3回答

长风秋雁

尝试这个import sysimport osimport randomimport timewhile 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 sysimport osimport randomimport timewhile 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

临摹微笑

最简单的,因为我不知道你为什么需要一个 try 语句:import ospath = input("Enter the path of your file (Remember to include the file "             "name and extension)")if os.path.exists():    passelse:    print("I did not find the file at, "+str(path))

慕村225694

import osfrom builtins import inputwhile 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python