Create a file if it doesn't exist

前端 未结 9 1797
悲哀的现实
悲哀的现实 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")
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题