How to create a new text file using Python

后端 未结 4 1003
抹茶落季
抹茶落季 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!

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-09 01:35
        file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
        any_string = "Hello\nWorld"
        file.write(any_string)
        file.close()
    
    0 讨论(0)
  • 2020-12-09 01:50

    Looks like you forgot the mode parameter when calling open, try w:

    file = open("copy.txt", "w") 
    file.write("Your text goes here") 
    file.close() 
    

    The default value is r and will fail if the file does not exist

    'r' open for reading (default)
    'w' open for writing, truncating the file first
    

    Other interesting options are

    'x' open for exclusive creation, failing if the file already exists
    'a' open for writing, appending to the end of the file if it exists
    

    See Doc for Python2.7 or Python3.6

    -- EDIT --

    As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

    with open("copy.txt", "w") as file:
        file.write("Your text goes here")
    
    0 讨论(0)
提交回复
热议问题