识别文件是否存在

时间:2019-02-22 20:08:07

标签: python python-3.x

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

编辑:添加错误类型

3 个答案:

答案 0 :(得分:2)

尝试一下

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

最简单的是,因为我不确定为什么需要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))