问题
I finally got my dbf file to be a csv but now I am confused as to how to parse this out into a text file for further editing.
I have been reading up on the csv module but to be honest my head began to spin. So much of it seemed Greek to me. However, I would like the code for using module this if possible.
My car.csv file looks like this:
Name,Total,Freq
Toyota,2,2
Mazda,1,1
Kia,2,1
Volkswagon,3,1
I want to output the following sentence into a text file (or csv):
Within this neighborhood there is a Toyota, Mazda, Kia, and Volkswagon parked on the street.
If the results are two I do not want commas:
Cars.dbf
Toyota,2,2
Mazda,2,1
Within this neighborhood there is a Toyota and Mazda parked on the street.
Cars.dbf
empty
There are no cars parked on the street within this neighborhood.
I got a good suggestion from a previous post on constructing the if-else sentences but am lost on how to parse columns (they didn't show up in Excel for some reason, I thought I only had one column)
python 2.7
BTW. Anyone know of a good web site that explains the csv module in terms a total newbie can understand? Thanks.
回答1:
The Python doc examples are always a go to place.
You want something like this:
import csv
makes = []
with open('cars.csv', 'rb') as f:
reader = csv.reader(f)
next(reader) # Ignore first row
for row in reader:
makes.append(row[0])
print makes
回答2:
Using the csv
module:
>>> with open('cars.csv') as f:
... reader = csv.reader(f)
... cars_list = [row[0] for row in reader]
...
>>> cars_list
['Name', 'Toyota', 'Mazda', 'Kia', 'Volkswagon']
回答3:
if I'm understanding correctly, you already have the csv file. If so, all you need to do is read it into whatever function(s) you're using to process it. Here's an example:
def process_csv():
with open('/path/to/file/car.csv') as f:
for line in f:
values_list = line.split(',') #gives you a list
#process your the rest here.
Basically, this loads your file and creates a list from each line. So for your Toyota,2,2
, you would end up with
> print('Name = " + values_list[0])
Name = Toyota
来源:https://stackoverflow.com/questions/15035660/parsing-out-single-column-from-csv-into-text-file-using-python