Section 12: File IO Flashcards
What is maintaining data?
- Until now, program short and produces some output then terminates: data produced disappears
- Data in our program uses is either hard-coded in the program, or received as input from user
Maintaining data: reading and writing text files
> Text File: sequence of characters stored in a permanent medium
Steps when working with files:
- Open file using build-in function
open()
- Read data from file
- Close file
Steps
How to open file using build-in function:
(1) fobj, (2) filename, (3) mode
```python
fobj = open(filename, mode)
~~~
-
fobj
: returns a file obejct use to read from file -
filename
: string corresponds to the name of the file that want to open- if the file is in the current dictionary: use its name
- if located somewhere elese: use full path to the file
-
mode
: Different permission modes:- ‘r’ for reading
- ‘w’ for writing
- ‘a’ for appending
Steps: Read/Writing data from file
(1) Read a file
-
read(size
) method that works on file objectsTakes one optional argument (size
: num of characters to read from the file → omitted, read whole thing) - Returns string containing characters of the file
Ex:
```python
filenam = ‘quotes.txt’
fobj = open(filename, ‘r’) #more r for reading
file_content = fobj.read() #read the whole thing
print(file_content) #print the string
~~~
Steps: Read/Writing data from file
(2) Reading a file line by line
- Object returned by
open()
is iterable sequence that produces the sequence of lines contained in the file - Can use a
for
loop to go over each line in the file
ex:
```python
filenam = ‘quotes.txt’
fobj = open(filename, ‘r’) #more r for reading
for line in fobj: #file object is iterable
print(line)
fobj.close() #closing the file
~~~
Steps: Read/Writing data from file
(3) Writing to a file
(1) Open file with open
using the mode 'w'
for ‘write’
- If the file does not exist, it will be created
- If the file does exist, it will be deleted and replaced with an empty file
(2) Can write(text)
method on the file object to write the string text into the file
(3) Close the file
```python
filenam = ‘quotes.txt’
fobj = open(filename, ‘r’) #more r for reading
fobj.write(“More first line in a file!)
fobj. write(“This will appear on the second line(?)”)
fobj.close()
~~~
Steps: Read/Writing data from file
Escape Characters
- In Python strings, the backslash
\
is special character: escape character-
\t
: tab character -
\n
: newline character
-
```python
fobj.write(‘cherry\tkiwi’)
~~~
Steps: Read/Writing data from file
Appending
(Add to the end of the file)
- Open the file with
open()
using mode'a'
for ‘append’. If it does not exist, it is created - Call
write(s)
method on the file object to insert the strings
at the end of the file - Close file
python filename = "quotes.txt" # assume it exists from last slide fobj = open(filename, "a") # mode "a" for appending fobj.write("\nA third line!! Will the madness ever stop?") fobj.close()
Steps
- Close file
close()
is a method that works on file objects. Takes no arguments and returns nothing. Closes the file
Why … ?
The OS may lock file till its close, too many open files may cause comp slow down, etc…
```python
filename = “quotes.txt”
fobj = open(filename, “r”) # mode “r” for reading
file_content = fobj.read() # read whole file
print(file_content) # print the string
fobj.close()
~~~
Opening Modes
Can also add a +
after the mode to indicate both reading and writing. r+
What is a Pickle Module
Another way to load/save data
> Pickle
module lets us load/save any Python object from/to a file
- Resulting file only be opened by Python (not regular text editing program)
What are the different parts of the Pickle Module:
-
import
pickle module to use it - Can put any data (x) in pickle file
- Name file using
data.pkl
extension - Use
'wb'
mode (write in binary) → data written in form of byte objects - Use
dump
method to save data x in file -
close()
file
Using pickle vs. regular file IO
- If writing data to a file and want other programs/people able to open file and read it → write directly in file using
open/write/close
- If you are writing data to a file that only your program will use → use pickle
What is CSV Formatting?
> Comma-Separate Values (CSV): file stores tabular data by sing commas to separate values
Ex: Movie 1,80,100,90,100 Movie 2,90,93,100,100 Movie 3,80,100,90,100
- Often used by program can export data
- Ex: Spreadsheet software (Excel, Numbers) can directly open CSV file
```python
»> read_csv(“movie_data.csv”)
[[“Movie 1”, “80”, “100”, “90”, “100”], [“Movie 2”, “90”, “93”,
“100”, “100”], [“Movie 3”, “80”, “100”, “90”, “100”]]
~~~