Create a file if it doesn't exist

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

    Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.

    import os
    
    with open("file.txt", 'w+') as f:
        f.write("file is opened for business")
    

提交回复
热议问题