Python file handling - writing
For code examples see Week4 Writing to Files Lab
Using 'w' mode
This time we use
w for write mode.
with open("/resources/data/Example2.txt", "w") as File1: File1.write("This is line A")
This will write
This is line A to the first line of the file, overwriting whatever was there before.
Successive calls of
.write() will write to a new line in the file.
Using 'a' mode
a mode will append lines to the end of an existing file.
It is also common to use for loops to add list or dictionary elements to a file.
with open("/resources/data/Example2.txt", "a") as File1: for item in source_list: File1.write(item)
You can nest file context managers to perform functions such as copying the contents of one file to another. See the graphic below.
- Open document (Hedgedoc) at https://doc.anagora.org/python-file-handling-writing
- Video call (Jitsi) at https://meet.jit.si/python-file-handling-writing