How to Write Files in Python

How to Write Files in Python

Python like many other languages has built-in functions to write files, to write a file we need first to open a file.>>> with open("t1.txt") as file:
... file.write("Hello world")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
io.UnsupportedOperation: not writable

Oh! wait it threw an error! why? the open command by default opens a file in “read” mode, so any write attempt will drive to an exception. There are two ways to open a file for writing and we need to be super-careful about what to choose when:

  • the write mode “w” this mode deletes any content of the file while opening the file, so use this mode when you are sure that you want to delete any previous content before writing.$ cat t1.txt
    line1
    line2
    line3kpatronas@prometheus:~$ python
    Python 3.8.10 (default, Mar 15 2022, 12:22:08)
    [GCC 9.4.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> with open("t1.txt","w") as file:
    ... file.write("hello")
    ...
    5
    >>> exit()
    kpatronas@prometheus:~$ cat t1.txt
    hello
  • The append mode “a” this mode appends any new .write() content to the end of the file.$ cat t1.txt
    line1
    line2
    line3
    kpatronas@prometheus:~$ python
    Python 3.8.10 (default, Mar 15 2022, 12:22:08)
    [GCC 9.4.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> with open("t1.txt","a") as file:
    ... file.write("hello\n")
    ...
    6
    >>> exit()
    kpatronas@prometheus:~$ cat t1.txt
    line1
    line2
    line3
    hello

$ ./buy-me-a-coffee ☕ // found this useful? I write these in my spare time