Create a file if it doesn't exist

前端 未结 9 1812
悲哀的现实
悲哀的现实 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条回答
  •  梦毁少年i
    2021-01-30 03:21

    Since Python 3.4, you can use the built-in library pathlib for creating the file if it doesn't exist in addition to the many other system call functions.

    from pathlib import Path
    
    fn = input("Enter file to open: ")
    
    Path(fn).touch() # File is only created if it doesn't exist (similar to touch command)
    

提交回复
热议问题