Programming Concepts 004 Flashcards
What is “with open” used for?
It is used for explicit opening and closing of text files.
What will this do?
with open(“test.txt”. ‘r’) as f:
file_content = f.read()
print(file_content)
It will open then print all the contents of test.txt.
What will happen?
with open(“test.txt”, ‘r’) as f:
file_content = f.read()
print(file_content)
print(f.read())
It will error as it is trying to access a closed file when it is printing.
What does read() do?
It reads a file as on single string.
What does readlines() do?
It reads every separate line and stores them in a list based on the next line character.
What does r and r+ do?
They both attempt to read a file but the + allows you to write to the file as well.
What does w and w+ do?
They both attempt to write to a file and also can make a new file but the + also allows for reading from a file.
What does a and a+ do?
They both act like w and w + where they write to a file but instead of overwriting everything it just adds to the end of the file.
What purpose do we write to and read files?
It can be used for getting data. This is like saving in a game for you stats and progression. It just means it can be continued after the program turns off.