File Modes
Start |
Read |
Write |
Create |
Truncate |
Cursor |
r |
* |
|
|
|
Start |
w |
|
* |
* |
* |
Start |
a |
|
* |
* |
|
End |
r+ |
* |
* |
|
|
Start |
w+ |
* |
* |
* |
* |
Start |
a+ |
* |
* |
* |
|
End |
x |
|
|
* |
|
Start |
readline()
with open('test.txt') as file:
file.readline()
file.readline(2) # 2 characters from line 2
file.readline(5) # 3 characters from line 3
file.readline()
file.readline()
'0 Start Line 0 - Line 0 End 0\n'
'1 '
'Start'
' Line 1 - Line 1 End 1\n'
''
|
If you call the readline() method multiple times, the reading will be continued at where it was read last time.
readline() method can also take in a size parameter, which will be used as a limit for reading the line. Again, reading is continued at where it was read last time.
Write a File
with open('test.txt', 'w') as file:
file.write('This is a writing method.')
25
|
The w mode will truncate the file, and thus the file will only contain the new values. The a mode will allow you to append new values to the existing file.
Printing the number of characters written can be suppressed by assigning the returned value to an underscore.
Reading Different Types of CSV
import csv
with open('addresses.csv', newline='') as addresses_csv:
address_reader = csv.DictReader(addresses_csv, delimiter=';')
for row in address_reader:
print(row['Address'])
|
We change the delimiters to indicate where the different values start and stop. We pass delimiter parameter, which is used to delineate separate fields in the CSV.
Writing a CSV File
big_list = [{'name': 'Fredrick Stein', 'userid': 6712359021, 'is_admin': False}]
import csv
with open('output.csv', 'w') as output_csv:
fields = ['name', 'userid', 'is_admin']
output_writer = csv.DictWriter(output_csv, fieldnames=fields)
output_writer.writeheader()
for item in big_list:
output_writer.writerow(item)
|
Open CSV in write mode, define fields, instantiate CSV writer object and pass two arguments.
.writeheader() writes headers from fieldnames.
|
|
Read File
with open('test.txt') as file:
file.read(6) # Size smaller than file size
'0 Star'
|
When the size argument is omitted or set as negative, or set as an integer greater than the file size, all the file contents will be read.
Reading a file for the second time will return an empty string.
readlines()
with open('test.txt') as file:
file.readlines()
# file.readlines(29) reads 29 characters, 30 reads whole of next line
['0 Start Line 0 - Line 0 End 0\n', '1 Start Line 1 - Line 1 End 1\n']
|
When size is set as a positive integer, it will read that many characters (or bytes in the binary mode) from the file and enough to complete that line.
writelines()
with open('test.txt', 'w') as file:
file.writelines(['Line 0\n', 'Line 1'])
with open('test.txt') as file:
file.read()
'Line 0\nLine 1'
|
This method will take in a list of strings as the parameter. How the lines are written (e.g., overwriting or appending) using this method is similar to the implementation of the write() method.
What is a CSV File?
Comma-Separated Values are usually the way that data from spreadsheet is exported into a portable format. |
Reading a CSV File
import csv
list_of_email_addresses = []
with open('users.csv', newline='') as users_csv:
user_reader = csv.DictReader(users_csv)
for row in user_reader:
list_of_email_addresses.append(row['Email'])
|
We can convert data into a dictionary using *csv and its DictReader object.
newline=""' ensures that we don’t mistake a line break in one of our data fields as a new row in CSV.
|