How to create a new text file using Python

后端 未结 4 1010
抹茶落季
抹茶落季 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:28

    # Method 1
    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 2
    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
    

    There are many more methods but these two are most common. Hope this helped!

提交回复
热议问题