I have a csv file. I need to iterate over each row accessing specific fields per row and use that data in the next stage.
Was thinking of using some numpy load csv method.
I have a csv file. I need to iterate over each row accessing specific fields per row and use that data in the next stage.
Was thinking of using some numpy load csv method.
This should work.
pip install csv
with open('my-csv-file.csv', newline='') as csvFile:
csvData = csv.reader(csvFile, delimiter=',', quotechar='|')
for row in csvData:
print(', '.join(row))
Numpy does offer a functionality for this. It's called np.loadtxt.
import numpy as np
# using loadtxt()
arr = np.loadtxt("sample_data.csv",
delimiter=",", dtype=str)
display(arr)
csv
libraryPython offers a csv library for this as well.
import csv
with open('sample_data.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print(', '.join(row))
Alternatively you don't actually need to use a third-party library. CSV is simply a text file with comma-separated values. Knowing this you can use the Python built in method to parse it.
with open("data.csv") as data:
for line in data:
items = [item for item in line.split(",")]
print(items)
The most popular library for tabular data handling is pandas
Sample data -
csv = '''"Header1", "Header2"
"Replace", 100
"string", 200
"with", 300
"file location", 400
"or url", 500'''
Code to only import one column -
import pandas
data = pandas.read_csv(csv, headers=["header1"]
printing data gives a table like
|"Header1" |
|----------------|
|"Replace" |
|"string" |
|"with" |
|"file location" |
|"or url" |
More info here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html