File Handling code - NOT IN SPEC NOW Flashcards
How to open a file?
Take variable, assign it to (open(“filename.txt”)), use one of the modes to open with, eg:
var = open("examplefile.txt","r")
Name the different modes and errors when opening a file:
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 to read everything in a file:
-open in read mode
-print it:
print(filevar.read())
-close file
How to read a specific line:
print ( filevar.readlines() [linenum] )
(note that it’s readlineS, not just readline)
-linenum will print the line number +1
-close file
How to write to a file:
-open file in either append or write mode (write will overwrite everything in it)
filevar.write("text")
-close file
How to close a file:
filevar.close()
How to add every line from a file into a list?
with open("words.txt", "r") as f: wordList = [line.strip() for line in f]
Line 2 removes the \n from each line