A basic example of reading and writing CSV files/data

This commit is contained in:
Junior 2024-06-26 11:06:22 -04:00
parent 5aa14f7b19
commit 60848a24e3
2 changed files with 69 additions and 0 deletions

64
Python/045_filedata.py Normal file
View File

@ -0,0 +1,64 @@
# File Data Input/Output
import os
from dataclasses import dataclass
from pathlib import Path
# We will start combining much of what we've learned so far
# as we begin talking about more complex subjects. The first
# example will be working with a CSV (Comma Separated Value)
# file used to store user data.
# We create a data class named User()
@dataclass
class User():
email: str = ""
id: int = 0
first_name: str = ""
last_name: str = ""
# Build up the path to the data file
data_file = os.path.join("Data", "users.csv")
# The pathlib module provides streamlined methods of getting
# the entire contents of a file in one command.
# This is a fairly complex statement.
# 1) Create a Path() object to the data_file
# 2) Use the read_text() method to read in the entire file as a string
# 3) Use the split() method on the string data to split it into lines
# 4) Use a slice ([1:]) to remove the first line (the header)
csv_contents = Path(data_file).read_text().split("\n")[1:]
# The list which will contain User() objects
users = []
# Step through the lines one at a time
for line in csv_contents:
# Split the line on commas after stripping leading/trailing white space
parts = line.strip().split(",")
# If we don't get four elements from the split then go to the next line
if len(parts) != 4:
continue
# Create a new User() object from the split parts of the line
users.append(User(parts[0], parts[1], parts[2], parts[3]))
# Print them out
for user in users:
print(user)
# Now we'll write the data we have back to a new file.
# In this repository any file beginning with "test_" will
# be ignored so we'll use a file names of "test_userdata.csv"
csv_filename = os.path.join("Data", "test_userdata.csv")
# We open the file. If the open fails it just quietly continues
with open(csv_filename, "w") as f:
# Let's write a header to the CSV
line = "EMail Address,User ID,First Name,Last Name\n"
f.write(line)
# Now we walk through the user data and write it all to the file
user: User
for user in users:
line = user.email + ","
line += user.id + ","
line += user.first_name + ","
line += user.last_name + "\n"
f.write(line)
print(f"User data written to file: {csv_filename}")

5
Python/Data/users.csv Normal file
View File

@ -0,0 +1,5 @@
Login email,Identifier,First name,Last name
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
mary@example.com,9346,Mary,Jenkins
jamie@example.com,5079,Jamie,Smith
1 Login email Identifier First name Last name
2 laura@example.com 2070 Laura Grey
3 craig@example.com 4081 Craig Johnson
4 mary@example.com 9346 Mary Jenkins
5 jamie@example.com 5079 Jamie Smith