Python csv without header

前端 未结 3 1379
死守一世寂寞
死守一世寂寞 2021-01-01 13:32

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, th

相关标签:
3条回答
  • 2021-01-01 14:04

    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']
    
    0 讨论(0)
  • 2021-01-01 14:11

    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]
    
    0 讨论(0)
  • 2021-01-01 14:30

    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.

    0 讨论(0)
提交回复
热议问题