Create a file if it doesn't exist

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

    '''
    w  write mode
    r  read mode
    a  append mode
    
    w+  create file if it doesn't exist and open it in (over)write mode
        [it overwrites the file if it already exists]
    r+  open an existing file in read+write mode
    a+  create file if it doesn't exist and open it in append mode
    '''
    

    example:

    file_name = 'my_file.txt'
    f = open(file_name, 'a+')  # open file in append mode
    f.write('python rules')
    f.close()
    

    I hope this helps. [FYI am using python version 3.6.2]

提交回复
热议问题