@@ -2532,4 +2532,47 @@ with open("haiku.txt", "w") as file:
25322532- r - Read a file (no writing) - this is the default
25332533- w - Write to a file (previous content is removed)
25342534- a - Append to the end of a file (previous content is not removed)
2535- - r+ - Read and write to a file (writes based on cursor - starts at beginning, only works with existing files)
2535+ - r+ - Read and write to a file (writes based on cursor - starts at beginning, only works with existing files)
2536+
2537+ ## Working with CSV
2538+
2539+ CSV files are a common file format for tabular data. The first row contains the headers, setting up what the data is.
2540+
2541+ You can read CSV files like any other file, but don't do this.
2542+
2543+ Python has a built-in CSV module to read/write CSVs more easily.
2544+
2545+ ` reader ` lets you iterate over CSV rows as lists.
2546+
2547+ ``` python
2548+ from csv import reader
2549+ with open " fighters.csv" as file :
2550+ csv_reader = reader(file )
2551+ next (csv_reader) # skip headers row
2552+ for fighter in csv_reader:
2553+ print (fighter) # each row is a list
2554+ print (f " { fighter[0 ]} is from { fighter[1 ]} " )
2555+ ```
2556+
2557+ ` DictReader ` lets you iterate over CSV rows as OrderedDicts.
2558+
2559+ ``` python
2560+ from csv import DictReader
2561+ with open " fighters.csv" as file :
2562+ csv_reader = DictReader(file )
2563+ for row in csv_reader:
2564+ print (row) # each row is an OrderedDict
2565+ print (row[" Name" ])
2566+ ```
2567+
2568+ ### Delimiters
2569+
2570+ Readers accept a delimiter kwarg in case your data isn't seperated by commas.
2571+
2572+ ``` python
2573+ from csv import reader
2574+ with open " example.csv" as file :
2575+ csv_reader = reader(file , delimiter = " |" )
2576+ for row in csv_reader:
2577+ print (row) # each row is a list
2578+ ```
0 commit comments