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:32

    I think this should work:

    #open file for reading
    fn = input("Enter file to open: ")
    try:
        fh = open(fn,'r')
    except:
    # if file does not exist, create it
        fh = open(fn,'w')
    

    Also, you incorrectly wrote fh = open ( fh, "w") when the file you wanted open was fn

提交回复
热议问题