为了账号安全,请及时绑定邮箱和手机立即绑定

判断文件是否存在

判断文件是否存在

PIPIONE 2021-11-16 18:19:19
我正在尝试确定文件是否存在,作为 Python 3.7.2 中错误处理过程的一部分。os.path.isfile()然而,作为我尝试使用的过程的一部分,我似乎在 if 语句中遇到了语法错误。我该如何解决这个问题,以便正确读取?代码是: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) == False:        print("I did not find the file at, "+str(user_input)                                                    # Checks if file is present        continue    else:        break编辑:包括错误类型
查看完整描述

3 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

尝试这个


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


查看完整回答
反对 回复 2021-11-16
?
临摹微笑

TA贡献1982条经验 获得超2个赞

最简单的,因为我不知道你为什么需要一个 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))


查看完整回答
反对 回复 2021-11-16
?
慕村225694

TA贡献1880条经验 获得超4个赞

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


查看完整回答
反对 回复 2021-11-16
  • 3 回答
  • 0 关注
  • 184 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信