Create a file if it doesn't exist

前端 未结 9 1932
悲哀的现实
悲哀的现实 2021-01-30 02:40

I\'m trying to open a file, and if the file doesn\'t exist, I need to create it and open it for writing. I have this so far:

#open file for reading
fn = input(\"         


        
9条回答
  •  抹茶落季
    2021-01-30 03:28

    First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.

    That said, you can do it as That One Random Scrub proposed, using try: ... except:. Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".

    But you can also easily test for existence:

    import os
    # open file for reading
    fn = raw_input("Enter file to open: ")
    if os.path.exists(fn):
        fh = open(fn, "r")
    else:
        fh = open(fn, "w")
    

    Note: use raw_input() instead of input(), because input() will try to execute the entered text. If you accidently want to test for file "import", you'd get a SyntaxError.

提交回复
热议问题