This note only exists for me to be able to learn it by heart via Flash Cards
flashcards, read a file in python
File reading modes
with open(filename, mode) as f:
data = f.read()
Modes:
String | Description |
---|---|
'r' | for reading text |
'w' | for writing |
'a' | for writing, will append to the file |
These basic commands can be extended with:
'+' | Allows for both reading and writing. However note, that the differences between 'r' and 'w' are kept, 'w+' still, deletes all content of the file, while 'r+' does not. |
---|---|
'b' | Binary mode: Opens or writes in binary mode. Essential, if the file contents are not characters. |
As an example, in the Pickling, saving objects to disk, you see that we use 'wb' to pickle an object. We only write, therefore 'w', and we might write non string data, so the binary extension: 'wb'
Read line by line
Assuming it is a text file:
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
# process each line