File I/O#
Overview#
At this point, you learned the main concepts to build your code, but our program is not using any data records or external information. This is why we should talk about the file operations, and we will discuss the simple file input/output for text (.txt) and comma-separated values (.csv) files, including reading, writing, and appending data, and managing file resources.
Working with Text file#
Things to know for .txt:
Opening a .txt file: you can use the built-in
open()
function, and has two parameters: path to file and mode (“r”: reading, “w”: writing, “a”: appending, or a combination of these options)
file = open("../_assets/myfile/myfile.txt", "r")
Reading a .txt file: To read the contents of a file, you can use various methods of the file object, such as read(), readline(), or readlines(). The read() method reads the entire content of the file as a string, while readline() reads a single line, and readlines() returns a list of all lines. Here’s an example
file = open("../_assets/myfile/myfile.txt", "r")
content = file.read()
print(content)
Hello, World!This is an additional line.
Writing to a .txt file: To write data to a file, you can open the file in write mode (“w”) and then use the write() method of the file object. If the file already exists, it will be overwritten. Here’s an example:
file = open("../_assets/myfile/myfile.txt", "w")
file.write("Hello, World!")
file.close()
Appending to a .txt file: To append data to an existing file, you can open the file in append mode (“a”) and then use the write() method. The new data will be added to the end of the file. Here’s an example:
file = open("../_assets/myfile/myfile.txt", "a")
file.write("This is an additional line.")
file.close()
Closing a .txt file: It is important to close the file after you finish working with it to release system resources. You can use the close() method of the file object to close the file explicitly. Here’s an example:
file = open("../_assets/myfile/myfile.txt", "r")
content = file.read()
print(content)
file.close()
Hello, World!This is an additional line.
Alternatively, you can use the with
statement to automatically close the file once you are done. Here’s an example:
with open("../_assets/myfile/myfile.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed outside the block
Hello, World!This is an additional line.
Working with CSV File#
Things to know for .csv:
Reading a .csv file: you can use the
csv
package (see how to install in ‘Advanced Topics’), andcsv.reader
(with ‘r’ mode == reading mode) creates a reader object that allows you to read line-by-line of the CSV data (loop in the reader object)
import csv
# Opening a CSV file for reading
file_csv=r'../_assets/myfile/uscounties.csv'
with open(file_csv, 'r') as file:
reader = csv.reader(file)
# Reading and printing all rows
for row in reader:
print(row)
['county', 'county_ascii', 'county_full', 'county_fips', 'state_id', 'state_name', 'lat', 'lng', 'population']
['Los Angeles', 'Los Angeles', 'Los Angeles County', '6037', 'CA', 'California', '34.3209', '-118.2247', '10019635']
['Cook', 'Cook', 'Cook County', '17031', 'IL', 'Illinois', '41.8401', '-87.8168', '5265398']
['Harris', 'Harris', 'Harris County', '48201', 'TX', 'Texas', '29.8577', '-95.3936', '4697957']
['Maricopa', 'Maricopa', 'Maricopa County', '4013', 'AZ', 'Arizona', '33.349', '-112.4915', '4367186']
['San Diego', 'San Diego', 'San Diego County', '6073', 'CA', 'California', '33.0343', '-116.735', '3296317']
['Orange', 'Orange', 'Orange County', '6059', 'CA', 'California', '33.7031', '-117.7609', '3182923']
['Kings', 'Kings', 'Kings County', '36047', 'NY', 'New York', '40.6395', '-73.9385', '2712360']
['Miami-Dade', 'Miami-Dade', 'Miami-Dade County', '12086', 'FL', 'Florida', '25.615', '-80.5623', '2690113']
['Dallas', 'Dallas', 'Dallas County', '48113', 'TX', 'Texas', '32.7666', '-96.7778', '2604722']
['Riverside', 'Riverside', 'Riverside County', '6065', 'CA', 'California', '33.7436', '-115.9938', '2409331']
Writing a .csv file: you can use
csv.writer
(with ‘w’ mode == writing mode) allows you to create a new empty file and write new lines withwriter.writerow()
. Note that we use a list() to add our values.
import csv
# Opening a CSV file for writing
file_csv=r'../_assets/myfile/data.csv'
with open(file_csv, 'w', newline='') as file:
writer = csv.writer(file)
# Writing headers
writer.writerow(['Name', 'Age', 'Country'])
# Writing data rows
writer.writerow(['John', 30, 'USA'])
writer.writerow(['Alice', 25, 'Canada'])
Appending data to a .csv file: you can use
csv.writer
(with ‘a’ mode == appending mode) allows you to add new line of data withwriter.writerow()
.
import csv
# Opening a CSV file for appending
file_csv = r'../_assets/myfile/data.csv'
with open(file_csv, 'a', newline='') as file:
writer = csv.writer(file)
# Appending additional data rows
writer.writerow(['Bob', 35, 'Australia'])
writer.writerow(['Emma', 28, 'UK'])
# Opening a CSV file for reading
with open(file_csv, 'r') as file:
reader = csv.reader(file)
# Reading and printing all rows
for row in reader:
print(row)
['Name', 'Age', 'Country']
['John', '30', 'USA']
['Alice', '25', 'Canada']
['Bob', '35', 'Australia']
['Emma', '28', 'UK']