# 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}")