Create a file if it doesn't exist

前端 未结 9 1795
悲哀的现实
悲哀的现实 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:36

    Well, first of all, in Python there is no ! operator, that'd be not. But open would not fail silently either - it would throw an exception. And the blocks need to be indented properly - Python uses whitespace to indicate block containment.

    Thus we get:

    fn = input('Enter file name: ')
    try:
        file = open(fn, 'r')
    except IOError:
        file = open(fn, 'w')
    

提交回复
热议问题