代码之家  ›  专栏  ›  技术社区  ›  Clauric

确定文件是否存在

  •  -2
  • Clauric  · 技术社区  · 7 年前

    作为Python 3.7.2中错误处理过程的一部分,我试图确定文件是否存在。作为过程的一部分,我尝试使用 os.path.isfile()

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

    代码是:

    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 回复  |  直到 7 年前
        1
  •  2
  •   Ankit Agrawal    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
    
        2
  •  1
  •   0x32e0edfb    7 年前
    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
    
        3
  •  1
  •   Chris Macaluso    7 年前

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