Create a file if it doesn't exist

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

    If you don't need atomicity you can use os module:

    import os
    
    if not os.path.exists('/tmp/test'):
        os.mknod('/tmp/test')
    

    UPDATE:

    As Cory Klein mentioned, on Mac OS for using os.mknod() you need a root permissions, so if you are Mac OS user, you may use open() instead of os.mknod()

    import os
    
    if not os.path.exists('/tmp/test'):
        with open('/tmp/test', 'w'): pass
    

提交回复
热议问题