So I have a.csv file with 35 columns, some of which I want to write to a database.
I only need about 4 of these columns - is it possible to just write say the 3rd value, the 25th value, and the 29th value in each row to a MySQL database?
Either that, or can I only write where the values are "Year", "Amount", and "Whatever"?
Now I know I could just truncate the Excel file, but its for a college assignment so I wanted to show a "techy" solution.
Maybe something like this?
desired_rows = [...] # Rows you'd like to read, 0-based
for number, row in enumerate(reader):
if not number in desired_rows:
continue
# Do stuff with the rows you want
....
You could use operator.itemgetter
to create a function that would retrieve all of the elements from each row each time it's called.
Something like the following. Note I subtract 1
from each column because the first column is at row index 0
, the second at index 1
, etc.
import csv
from operator import itemgetter
COLS = 3, 25, 29
filename = 'columns.csv'
getters = itemgetter(*(col-1 for col in COLS))
with open(filename, newline='') as csvfile:
for row in csv.reader(csvfile):
print(getters(row))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.