Writing to a File
Now we have understood the basics of Programming through Python, we will dig deeper into some of the practical use of this. Python comes with rich set of libraries using which we can use. We will talk about reading and writing to a file. Let’s see how this is done in Python.
Assume you have a folder in C: (for Windows operating system). Create a folder called temp. So the fullpath of the folder would become C:\temp.
If you do not have the temp folder created then the below code will not work. You can use any other folder of your choise. Just make sure that it exists. If not then first create it.
Write to a file
To write to a file called myfile.txt
# Write to a file
filename = "C:\\temp\\myfile.txt"
f=open(filename,"w")
f.write("Hello from code to write to a file.")
f.close()
If you do not have the file already created this will create the file before wrting on to it.
You need to make sure that you call
f.close()
Append to a File
If you want to add another text to the same file then you need to use append (a
). If you continue to use (w
) then the file will be overridden.
filename = "C:\\temp\\myfile.txt"
f = open(filename, "a+")
f.write("\rAnother line")
f.close()
By using
a+
you are basically opening a file both read and write mode. You can also usew+
which would open a file in both read and write mode.
Writing multiple lines at a time
When you have to write to a file line by line then you can open file once and write them one by one. You do not need to open a file in
write
mode then inappend
mode.
filename = "C:\\temp\\myfile2.txt"
f = open(filename, "w")
lines = ["Line1\n", "Line2\n", "Line3\n"]
f.writelines(lines)
f.close()
Notice here we have added
\n
at the end of each items. This indicates a newline in a file. You can also construct the text to write to file with new line and then write at once by callingwrite(val)
method.