Python Forum
How to print a column name in csv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print a column name in csv file
#1
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.
Reply
#2
with open('googleplaystore.csv') as fp:
    reader = csv.reader(fp):
    header = next(reader)
    print(f"header: {header}")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding the median of a column in a huge CSV file markagregory 5 1,733 Jan-24-2023, 04:22 PM
Last Post: DeaD_EyE
  Filter data based on a value from another dataframe column and create a file using lo pawanmtm 1 4,245 Jul-15-2020, 06:20 PM
Last Post: pawanmtm
  DataFrame: To print a column value which is not null out of 5 columns mani 2 2,078 Mar-18-2020, 06:07 AM
Last Post: mani
  Change column names from a file Nidhesh 2 2,962 Jul-08-2019, 06:00 AM
Last Post: Nidhesh
  copy one column from csv file and paste into xls file kprogrammer 0 4,346 Nov-03-2018, 04:03 PM
Last Post: kprogrammer
  Upload csv file as numbers (floating?) and extract element, row, and column bentaz 7 4,414 Mar-19-2018, 05:34 PM
Last Post: bentaz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020