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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to check CWD

A

impost os

os. getcwd()
os. chdir(‘/-/-/-/’) # Change directory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write into a data file

A

.write() # used to write lines of text

- end file writing by using my_file.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

file reading exceptions

A

use try and except for example is the file is empty, or the file does not exist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

exception classes

A

there are many exception classes derived from base exceptions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly