Reading files
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A file is opened with the open() function. The right way is with with: then the file closes by itself, even if an error happens inside.
with open("notes.txt", encoding="utf-8") as f:
text = f.read() # the whole file as one string
Other ways to read:
with open("notes.txt", encoding="utf-8") as f:
lines = f.readlines() # a list of lines, each ending with '\n'
with open("notes.txt", encoding="utf-8") as f:
for line in f: # line by line — the best option for big files
print(line.rstrip("\n"))
Always specify encoding="utf-8". Otherwise, on Windows, non-English text can come out as gibberish: the default encoding there is different.
If the file doesn't exist, you get a FileNotFoundError. The path is written relative to the folder the program was started from, or in full: /home/user/notes.txt.
Task. The setup code has already written the input to the file notes.txt. Read it and print every non-empty line with a number: 1. buy bread.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.