How to create a new text file using Python

后端 未结 4 1054
抹茶落季
抹茶落季 2020-12-09 01:00

I\'m practicing the management of .txt files in python. I\'ve been reading about it and found that if I try to open a file that doesn\'t exists yet it will create it on the

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 01:32

    f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
    f.write("Hello World from " + f.name)    # Write inside file 
    f.close()                                # Close file 
    
    # Method 2shush
    with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
        f.write("Hello World form " + f.name)       # Writing
    # File closed automatically
    

提交回复
热议问题