Python - File I/O Flashcards
How do you do the most basic File Opening, saving to a variable the text file, printing the text, and closing that file?
data_file = open('data.txt') # notice that data_file is an instance of this io class!
# we can access the methods of this class like usual # with the dot operator text = data_file.read()
# you need to always do this data_file.close()
What’s another way to open a text file and print each line, line-by-line using for loops?
data_file = open(‘data.txt’)
for line in data_file:
print(line)
notice how data_file is an iterable!
When saving the text file opened using the open method to a variable, what is the type of that variable?
It is an instance of the I/O class. Specifically it is an iterable (from which you can loop over too!)
What is the number of characters in our first line if our text file is given below? What is the number of total characters? What characters are unseen? How do we get rid of this first extra unseen character when reading in our text file?:
10 20 30
14 40 70
There are a total of 17 characters (numbers, spaces, and new line char). The first line contains 9 characters, the second line contains 8 characters. At the end of the first line there is a new line character. We can use the strip() method to get rid of extra new line character in each line, since each line is of the type string.
What does the second argument to the open() function do?
It indicates the mode in which the file should be opened.
Suppose the file output.txt initially has one line in it containing three letters: “abc”. What is in the file after the program below runs?
with open(‘output.txt’, ‘w’) as f:
f. write('def') f. write('ghi')
defghi
it overwrites the previous stuff in the file, and also no new line characters are inputted
The following program tries to print the contents of a file called file.txt. See if you can fix it!
my_file = open(‘file.txt’)
print(my_file)
my_file = open(‘file.txt’)
my_file = my_file.read()
print(my_file)
Suppose you have a file called numbers.txt that has lists of three integers per line, like this:
10 20 23
-7 8 15
0 12 -51
17 -12 -1
There may also be more or fewer than four lines. However, each line contains exactly three integers. Write a program that computes the sum of each row and outputs that sum to another file called output.txt.
For the file above, output.txt should contain the following when your program is finished:
63
16
-39
4
opens and saves a list of the lines of the file
with open('file.txt', 'r') as f: list_of_lines = f.readlines()
converts each line to a list of strings
list_of_lists_of_strings = [string.split() for string in
list_of_lines]
converts each line/list of strings to a list of ints
list_of_lists_of_ints = []
for list_of_strings in list_of_lists_of_strings:
list_of_ints = [int(i) for i in list_of_strings]
list_of_lists_of_ints.append(list_of_ints)
converts each list of ints to a sum then stringifies that sum
list_of_sums = []
for list_of_ints in list_of_lists_of_ints:
list_of_sums.append(str(sum(list_of_ints)) + ‘\n’)
now that we have a list of stringified sums we write it out to a file
with open('output.txt', 'w') as f: f.writelines(list_of_sums)
# This program tries to write the word "hi" to # a file named file.txt. See if you can fix it!
with open('file.txt', 'w') as output_file: output_file.print('hi')
# This program tries to write the word "hi" to # a file named file.txt. See if you can fix it!
with open('file.txt', 'w') as output_file: output_file.write('hi')
How would you open a file and not rewrite over it, but append new text to it?
output_file = open(‘output_file.txt’, ‘a’)
output_file.write(‘\nnew stuff’)
output_file.close()
What do these optional set parameters do?
"r" - "x" - "t" - "b" - "+" - "w" - "a" -
“r” - opens file for reading
“x” - create a new file, don’t create if already exist
“t” - want to treat file as text and not binary
“b” - treat file as binary
“+” - for reading and writing (adds the one that is
missing)
“w” - opens a file for write mode, overwrites it if exists
otherwise if it doesn’t exist it creates one
“a” - opens a file for appending at the end of the file.
Creates a new file if it doesn’t exist.
You can also mix and match and combine them
Which command automatically brings the cursor to that spot in the file?
file_name.seek ( some_index )
*It doesn’t return anything. Just does that action.
Which command automatically returns the current position of the cursor?
file_name.tell()
*Returns the current cursor position
Which command returns the current line where the cursor is at in the file?
file_name.readline()
*Returns the current line where the cursor is at as a string
How do we pickle this dictionary?
phone_book = {
‘Jonathan’: ‘444-555-6666’,
‘Elmo’: ‘777-555-3333’
}
import pickle
with open(‘phone_book_file’, ‘wb’) as pbf:
pickle.dump(phone_book, pbf)
____
(where phone_book is the dictionary, and pbf is the file name)