Python - File I/O Flashcards

1
Q

How do you do the most basic File Opening, saving to a variable the text file, printing the text, and closing that file?

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

What’s another way to open a text file and print each line, line-by-line using for loops?

A

data_file = open(‘data.txt’)

for line in data_file:
print(line)

notice how data_file is an iterable!

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

When saving the text file opened using the open method to a variable, what is the type of that variable?

A

It is an instance of the I/O class. Specifically it is an iterable (from which you can loop over too!)

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

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

A

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.

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

What does the second argument to the open() function do?

A

It indicates the mode in which the file should be opened.

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

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')
A

defghi

it overwrites the previous stuff in the file, and also no new line characters are inputted

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

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)

A

my_file = open(‘file.txt’)
my_file = my_file.read()
print(my_file)

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

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

A

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

How would you open a file and not rewrite over it, but append new text to it?

A

output_file = open(‘output_file.txt’, ‘a’)

output_file.write(‘\nnew stuff’)

output_file.close()

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

What do these optional set parameters do?

"r" - 
"x" - 
"t" - 
"b" -
"+" - 
"w" - 
"a" -
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

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

Which command automatically brings the cursor to that spot in the file?

A

file_name.seek ( some_index )

*It doesn’t return anything. Just does that action.

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

Which command automatically returns the current position of the cursor?

A

file_name.tell()

*Returns the current cursor position

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

Which command returns the current line where the cursor is at in the file?

A

file_name.readline()

*Returns the current line where the cursor is at as a string

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

How do we pickle this dictionary?

phone_book = {
‘Jonathan’: ‘444-555-6666’,
‘Elmo’: ‘777-555-3333’
}

A

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)

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

How do we unpickle a file called ‘pbf’ as a variable named ‘new_phone_book’, and print that as a string?

A
with open('phone_book_file', 'rb') as pbf:
  new_phone_book = pickle.load(pbf)

print(new_phone_book)
____
returns a string consisting of the text in the file pbf

17
Q

Do we need to use binary ‘b’ mode when pickling?

A

Yes, we always need to use ‘b’ mode when pickling.

18
Q

______ is used for serializing and de-serializing Python object structures, also called marshalling or flattening. Serialization refers to the process of converting an object in memory to a byte stream that can be stored on disk or sent over a network. Later on, this character stream can then be retrieved and de-serialized back to a Python object.

A

Pickle is used for serializing and de-serializing Python object structures, also called marshalling or flattening. Serialization refers to the process of converting an object in memory to a byte stream that can be stored on disk or sent over a network. Later on, this character stream can then be retrieved and de-serialized back to a Python object.

19
Q

What’s the basic template/format for manipulating files open and closed with pickling?

A
#### read from files
try: 
    with open('names_list', 'rb') as f:
        data = pickle.load(f)
except FileNotFoundError:
    data = []
#### do actions on that data
next_name = input('Enter a name: ')
data.append(next_name)
print(data)
#### record what you did in the file
with open('names_list', 'wb') as f:
    pickle.dump(data, f)
20
Q
# This program tries to write and then read back a
# dictionary using the pickle module. See if you can
# fix it!

import pickle

original_dictionary = {'a': 1, 'b': 2}
with open('stored_dictionary', 'w') as pickle_file:
    pickle.dump(original_dictionary, pickle_file)
with open('stored_dictionary') as pickle_file:
    new_dictionary = pickle.load(pickle_file)
    print(new_dictionary == original_dictionary)
A
# This program tries to write and then read back a
# dictionary using the pickle module. See if you can
# fix it!

import pickle

original_dictionary = {'a': 1, 'b': 2}
with open('stored_dictionary', 'wb') as pickle_file:
    pickle.dump(original_dictionary, pickle_file)
with open('stored_dictionary', 'rb') as pickle_file:
    new_dictionary = pickle.load(pickle_file)
    print(new_dictionary == original_dictionary)
21
Q

What does f.read() do?

A

reads the entire file into memory and returns an individual string

22
Q

What does f.readline() do?

A

reads the current line into memory, and returns a string of that line

23
Q

What does f.readlines() do?

A

reads the whole file into memory, parses it into lines, and returns a list full of strings out of those lines

***very memory intensive!!!

24
Q

What type of object does the open() function return?

A

A file object (which is also an iterable btw)

25
Q

After opening a file and saving it with a variable name, how do we write to that file?

file = open(“testfile.txt”,”w”)

A

Use the write() method:

file = open(“testfile.txt”,”w”)

file.write(“Hello World”)

26
Q

After opening a file and saving it with a variable name, how do we write MULTIPLE LINES of text to that file?

file = open(“testfile.txt”,”w”)

A

Save the text as strings in a list and then use the writelines() method:

fh = open(“hello.txt”,”w”)

lines_of_text = [“One line of text here”, “and another line here”, “and yet another here”, “and so on and so forth”]

fh. writelines(lines_of_text)
fh. close()

27
Q

Name 3 advantages of saving a file in JSON format over pickling it to BINARY format?

A

JSON advantages:

1) Standardized / Language Independent
2) Easily readable by humans (binary file isn’t)
3) More secure + faster

28
Q

What method would you use in the pickle module to write a file to binary?

filename = 'dogs'
outfile = open(filename,'wb')
A

After opening the file in write binary mode you use pickle dump:

filename = 'dogs'
outfile = open(filename,'wb')

pickle. dump(dogs_dict,outfile)
outfile. close()

_____

Once the file is opened for writing, you can use pickle.dump(), which takes two arguments: the object you want to pickle and the file to which the object has to be saved.

29
Q

How would you go about unpickling a file?

infile = open(filename,’rb’)

A

After opening the file in read binary mode you use pickle load:

infile = open(filename,’rb’)

new_dict = pickle.load(infile)

infile.close()

30
Q

What are the 3 main pickle methods?

A

string_of_data = pickle.load(file_name)

string_of_data.append(some_new_string)

pickle.dump(string_of_data, file_name)

31
Q

How can you work with 2 files at the same time?
How would you read from the first file and write the reversed text to the second file?

d_path = ‘dog_breeds.txt’
d_r_path = ‘dog_breeds_reversed.txt’

A
d_path = 'dog_breeds.txt'
d_r_path = 'dog_breeds_reversed.txt'
with open(d_path, 'r') as reader, open(d_r_path, 'w') as writer:
    dog_breeds = reader.readlines()
    writer.writelines(reversed(dog_breeds))