33

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.

1

4 Answers 4

55

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]
Sign up to request clarification or add additional context in comments.

Comments

6

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']

Comments

0

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 ;)

Comments

-3

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.

1 Comment

your code is reading sql though? And writing to csv? Did you read the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.