Open, read & write (and append) content/files with Python

How to open a file?

With the following code, you open and read the content of a file

with open("text.txt", "r") as file:
  print(file.read())

You obtain a list of the lines in the file with this

with open("text.txt", "r") as file:
  print(file.readlines())

You read one line at the time with this

with open("text.txt", "r") as file:
  print(file.readline())

You can print the lines simply like this:

with open("text.txt", "r") as file:
  for line in file:
    print(line)

Write a file

with open("text.txt", "w") as file:
  file.write("Hello world")

Append a text to a file

with open("text.txt", "a") as file:
  file.write("This does not cancel the file content")

Live code video about opening and writing files

https://pythonprogramming.altervista.org/how-to-create-a-list-of-tuple-from-a-string-pythonically/

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.