简体   繁体   中英

Readline to Array or List output

I am new to Python and was recently given a problem to solve.

Briefly, I have a.csv file consisting of some data. I am supposed to read the.csv file and print out the first 5 column header names, followed by 5 rows of the data in the following format shown in the picture. Results

Currently, I have written the code up to:

readfiles = file.readlines()
for i in readfiles:
    data = i.strip()
    print(data)

and have managed to churn out all the data. However, I am not too sure how I can get the 5 rows of data which is required by the problem. I am thinking if the.csv file should be converted into an array/list? Hoping someone can help me on this. Thank you.

I can't use pandas or csv for this by the way. =/

df = pd.read_csv('\#pathtocsv.csv')
df.head()

if you want it in list

needed_list = df.head().tolist()

First of all, if you want to read a csv file, you can use pandas library to do it.

import pandas as pd

df = pd.read_csv("path/to/your/file")
print(df.columns[0:5]) # print first 5 column names
print(df.head(5)) # Print first 5 rows

Or if you want it to do without pandas then,

rows = []
with open("path/to/file.csv", "r") as fl:
    rows = [x.split(",") for x in fl.read().split("\n")]
print(rows[0][0:5]) # print first 5 column names
print(rows[0:5]) # print first 5 rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM