Reputation: 3955
With header information in csv file, city can be grabbed as:
city = row['city']
Now how to assume that csv file does not have headers, there is only 1 column, and column is city.
Upvotes: 33
Views: 101189
Reputation: 311
For CSV file does not have headers, and there is more than 1 column, can add your other column names in order in the fieldnames=[]
Background: I have a CSV of consisitng of hostname, followed by respective IP.
e.g.
PLNXXXXA, 10.10.10.1
PLNXXXXB, 10.10.10.2
I want to build my lookup that key is IP, and respective value is hostname to enrich my data. Below are the code:
import csv
csv_file =r"4.1.6_lookup.csv"
# Initialize an empty lookup dictionary
lookup = {}
# Read from the CSV file and populate the lookup dictionary
with open(csv_file, 'r') as f:
csv_reader = csv.DictReader(f,fieldnames=['hostname','IP'])
for row in csv_reader:
# Capitalize the hostname and remove any leading/trailing whitespaces
hostname = row['hostname'].upper().strip()
lookup[row['IP']] = hostname
The output is going to be like:
{'10.10.10.1': 'PLNXXXXA', '10.10.10.2': 'PLNXXXXB'}
Hope this helps someone. Thank you ;)
Upvotes: 0
Reputation: 185
You can use pandas.read_csv() function similarly to the way @nosklo describes, as follows:
df = pandas.read_csv("A2", header=None)
print df[0]
or
df = pandas.read_csv("A2", header=None, names=(['city']))
print df['city']
Upvotes: 6
Reputation: 21
I'm using a pandas dataframe object:
df=pd.read_sql(sql_query,data_connection)
df.to_csv(filename, header=False, index=False)
Don't know if that is the most Pythonic approach, but it gets the job done.
Upvotes: -3
Reputation: 222862
You can still use your line, if you declare the headers yourself, since you know it:
with open('data.csv') as f:
cf = csv.DictReader(f, fieldnames=['city'])
for row in cf:
print row['city']
For more information check csv.DictReader
info in the docs.
Another option is to just use positional indexing, since you know there's only one column:
with open('data.csv') as f:
cf = csv.reader(f)
for row in cf:
print row[0]
Upvotes: 55