Writing to a file

To write a line to a file you use the write() function on the file handler.

lines_to_write = ["This is the first line.", 
                          "The second line",
                          "And the third line"]

with open("data2.txt", "w") as input_file:
    for line in lines_to_write:
        input_file.write(str(line) + "\n")

Notice the special \n character we add to each line. This is a hidden character that signifies a new line. Remember that writing to a file removes the current contents of the file and overwrites with the new data.


Try the following:

string_to_write = "Hello World!"
with open("HelloWorld.txt", "wt") as file_handler:
    file_handler.write(string_to_write + "\n")
print("File written")

The file should be made within the same directory as the Python script. Open up the HellowWorld.txt file and check the contents.

Report a Glow concern
Cookie policy  Privacy policy