Create a file if it doesn't exist

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

    Using input() implies Python 3, recent Python 3 versions have made the IOError exception deprecated (it is now an alias for OSError). So assuming you are using Python 3.3 or later:

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

提交回复
热议问题