Python Forum

Full Version: How to print a column name in csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Among other things ( open data sets, explore them, print the first few rows and number of rows and columns ) I should print names of columns
my code looks like this:
def explore_data(dataset, start, end, rows_and_columns=False):
    dataset_slice = dataset[start:end]
    for row in dataset_slice:
        print(row)
        print('\n')  # adds a new (empty) line after each row
    
    if rows_and_columns == True:
        print('Number of rows:', len(dataset))
        print('Number of columns:', len(dataset[0]))
                            
from csv import reader

open_file1 = open('googleplaystore.csv')
read_file1 = reader(open_file1)
android = list(read_file1)
android_header = android[0]
android = android[1:]

open_file2 = open('AppleStore.csv')
read_file2 = reader(open_file2)
apple = list(read_file2)
apple_header = apple[0]
apple = apple[1:]

first = explore_data(android, 1, 3, rows_and_columns=True)
second = explore_data(apple, 1, 3, rows_and_columns=True)
I can't figure out how to print just column names. These two files are regular csv.
I tried smth with
for col_name in row[0]:
    print(col_name)
within a defined function but it gave me uglu result.
with open('googleplaystore.csv') as fp:
    reader = csv.reader(fp):
    header = next(reader)
    print(f"header: {header}")