In Module 3: lesson 2, we are relying on the helper functions for opening and reading files in python. I’m going through the helper function.py file to understand how I would do this without relying on the helper functions and it appears there are long-winded functions for doing so. Do these need to be defined everytime we write our own code requiring external files or is there a library that contains functions that can look after these for us?
I’m assuming the libraries we require to open and read files are:
- import io
- import csv
Here are the code blocks for opening and reading files:
def read_csv_dict(csv_file_path):
“”“This function takes a csv file and loads it as a dict.”“”
# Initialize an empty list to store the data
data_list = []
# Open the CSV file
with open(csv_file_path, mode='r') as file:
# Create a CSV reader object
csv_reader = csv.DictReader(file)
# Iterate over each row in the CSV file
for row in csv_reader:
# Append the row to the data list
data_list.append(row)
# Convert the list to a dictionary
data_dict = {i: data_list[i] for i in range(len(data_list))}
return data_dict
def upload_txt_file():
"""
Uploads a text file and saves it to the specified directory.
Args:
directory (str): The directory where the uploaded file will be saved.
Defaults to the current working directory.
"""
# Create the file upload widget
upload_widget = widgets.FileUpload(
accept='.txt', # Accept text files only
multiple=False # Do not allow multiple uploads
)
# Impose file size limit
output = widgets.Output()
# Function to handle file upload
def handle_upload(change):
with output:
output.clear_output()
# Read the file content
content = upload_widget.value[0]['content']
name = upload_widget.value[0]['name']
size_in_kb = len(content) / 1024
if size_in_kb > 3:
print(f"Your file is too large, please upload a file that doesn't exceed 3KB.")
return
# Save the file to the specified directory
with open(name, 'wb') as f:
f.write(content)
# Confirm the file has been saved
print(f"The {name} file has been uploaded.")
# Attach the file upload event to the handler function
upload_widget.observe(handle_upload, names='value')
display(upload_widget, output)