read a csv file in python

To read a CSV (Comma-Separated Values) file in Python, you can use the built-in csv module.

  1. First, import the csv module:
main.py
import csv
11 chars
2 lines
  1. Open the CSV file using open() function with 'r' (read) mode:
main.py
with open('file.csv', 'r') as file:
    csv_reader = csv.reader(file)
70 chars
3 lines
  1. Read the contents of the CSV file line by line using a for loop:
main.py
with open('file.csv', 'r') as file:
    csv_reader = csv.reader(file)
    
    for line in csv_reader:
        print(line)
123 chars
6 lines

This will print each line of the CSV file as a list of values.

  1. If your CSV file has a header row, you can use the next() function to skip it:
main.py
with open('file.csv', 'r') as file:
    csv_reader = csv.reader(file)
    
    # Skip header row
    next(csv_reader)
    
    for line in csv_reader:
        print(line)
171 chars
9 lines
  1. To read a CSV file with a different delimiter character (e.g. tab), you can pass it as an argument to the csv.reader() function:
main.py
with open('file.tsv', 'r') as file:
    csv_reader = csv.reader(file, delimiter='\t')
    
    for line in csv_reader:
        print(line)
139 chars
6 lines

This will read a TSV (Tab-Separated Values) file instead of a CSV file.

related categories

gistlibby LogSnag