About the author
Now that you can read data from a file, its time to write data in the file. To write data you need 'write' function. When we open a file by default it is read-only mode.
file = open('filename.txt')
But if we want to write we need to specify the mode for write or append.
file = open('filename.txt', 'w')
file = open('filename.txt', 'a')
You can use any one of them, 'w' (write) is used when you want to write in a new file or empty old and write new data, 'a' (append) is used when you don't want to erase old data and add new data.
Below example will clear more:
The filename is "pyfourm.txt".
In line 3 and 4 we added extra "\n" so that the next data will be written in the next line.
Let's see the output
Now let's create a small command-line text editor.
You can download this code here.
You can download this code here. Let's understand this better.
Line 10: While Loop, To manage error. we created this loop to make sure that user enter only w or a in response. If user enter some thing else loop will continue. Their is better method to manage these called try:except, but that will be covered in later chapter.
Line 13, 16: File will open as per user requirements.
Line 20: We defined a variable to store all data and then write all at once in the file.
Line 27: Adding new data in datatowrite variable which have all old data.
Line 29: Writing all data in the file
Line 30: Closing file, it is always recommended to close the file once your work is done, whether its for reading or writing purpose.
Note: We could write directly in the file at line 27 instead of defining variable datatowrite. That may seams easy way, but when you are in production it is not wise to write multiple time in file, this will provide I/O delay which could cause your code to run slow. In testing purpose you can use any method. If we want to write directly then line 27 will be.
file.write("%s\n" % (newdata))
Try some read and write from files.
About the author
Please login to comment