How to read and write files in Python

Open file

with open("text.txt", "r", encoding="utf-8") as file:
    file = file.read()

Use with, so that the file will be closed automatically when you finish the read() operation. At the end, you will get a string in the file variable that contains the text in the text.txt file.

The ‘r’ parameter is for read, so that you cannot write in the file in this mode. ‘w’ is for write mode. ‘a’ is for append mode.

 

Write in a file

with open("text.txt", "w", encoding="utf-8") as file:
    file.write("This are words written in text.txt")

Now we’ve written something in the file. If there was something before, now it’s all gone. To add things to a file, use ‘a’, instead of ‘w’.

with open("text.txt", "w", encoding="utf-8") as file:
    file.write("This are words written in text.txt")

Opend a file and have a list of the lines

with open("text.txt", "w", encoding="utf-8") as file:
    file = file.readlines()

Now you have a list of lines (from the file content) in file, instead of a string (like in the read() function mode).

Utilities

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.