To write to a file, use the write() function. This function takes a string as its parameter, and writes
the string to its associated output file.
For example, here is a simple program that opens a file
for writing, and then writes two strings to the file:
myfile = open("myfile.txt", "w")
data = "Here is a line of text being written to a file. "
data2 = "Here is some more data."
myfile.write(data)
myfile.write(data2)
Note that this program writes the two strings to the same output line. The output file looks like this:
Here is a line of text being written to a file. Here is some more data.
To write the strings on separate lines, add
a newline character, represented by \n, to the end of the first string:
myfile = open("myfile.txt", "w")
data = "Here is a line of text being written to a file.\n"
data2 = "Here is some more data."
myfile.write(data)
myfile.write(data2)
You cannot write to a file unless it has been opened. See Opening a File
for details on how to open a file.