File Handling code - NOT IN SPEC NOW Flashcards

1
Q

How to open a file?

A

Take variable, assign it to (open(“filename.txt”)), use one of the modes to open with, eg:

var = open("examplefile.txt","r")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Name the different modes and errors when opening a file:

A

r - read (errors if no file found)
a - creates if no file found, and appends text
w - creates if no file found, and overwrites everything currently inside
x - creates file, but errors if it already exists

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

How to read everything in a file:

A

-open in read mode
-print it:

print(filevar.read())

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

How to read a specific line:

A
print ( filevar.readlines() [linenum] )

(note that it’s readlineS, not just readline)

-linenum will print the line number +1
-close file

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

How to write to a file:

A

-open file in either append or write mode (write will overwrite everything in it)

filevar.write("text")

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

How to close a file:

A
filevar.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to add every line from a file into a list?

A
with open("words.txt", "r") as f:
    wordList = [line.strip() for line in f]

Line 2 removes the \n from each line

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