File Input/Output Flashcards
1
Q
How to create a file
A
- create variable to assign text file to
- open(‘TEXTFILENAME.TXT’, ‘READWRITEAPPEND’)
- this makes an empty file in the current folder
- using w overwrites anything previously written in the file
2
Q
How to check CWD
A
impost os
os. getcwd()
os. chdir(‘/-/-/-/’) # Change directory
3
Q
Write into a data file
A
.write() # used to write lines of text
- end file writing by using my_file.close()
4
Q
Read data out of the text file
A
- create empty variable
- open file
- assign a variable to file.readline()
- while the variable holding the line is not empty
- append the line.rstrip() (to remove empty characters) to empty variable and repeat the step (appending each line through iteration)
- close file
5
Q
file reading exceptions
A
use try and except for example is the file is empty, or the file does not exist
6
Q
exceptions
A
- a situation that can cause a program to start acting erratically or to crash entirely
- using try and except works to solve these issues
- EAFP (easier to ask forgiveness than permission)
7
Q
exception classes
A
there are many exception classes derived from base exceptions
8
Q
try and except
A
- more than one except block may be used if it is anticipated that more than 1 class of error may be encountered
- when used by itself, except encounters all exceptions