How do I check whether a file exists without exceptions?

后端 未结 30 1953
北海茫月
北海茫月 2020-11-21 05:07

How do I check if a file exists or not, without using the try statement?

30条回答
  •  清酒与你
    2020-11-21 05:30

    If the file is for opening you could use one of the following techniques:

    with open('somefile', 'xt') as f: #Using the x-flag, Python3.3 and above
        f.write('Hello\n')
    
    if not os.path.exists('somefile'): 
        with open('somefile', 'wt') as f:
            f.write("Hello\n")
    else:
        print('File already exists!')
    

    UPDATE

    Just to avoid confusion and based on the answers I got, current answer finds either a file or a directory with the given name.

提交回复
热议问题