Search code examples
pythoncsvnewlinereadfile

Reading csv files with new lines


I want to read the CSV file that i have created, and have it printed on new lines:

this is the code

rows = []
with open("test.csv", 'r') as file:
    csvreader = csv.reader(file)
    header = next(csvreader)
    for row in csvreader:
        rows.append(row)
print(header)
print(rows)

the output I get is this...

['TeamName', 'MCount']
[[], ['team One', '23'], ['Team Two', '102'], ['Team Three', '44'], ['Team Four', '40']]

I want it to look like this:

Team One 23    
Team Two 102    
Team Three 44    
Team Four 40

Solution

  • This method will print in the format you requested and number your rows as well.

    import pandas as pd
    
    data = pd.read_csv('test.csv', header = None, names = ['Team Name', 'Number', 'Score'])
    
    print(data)
    

    Output:

          Team Name  Number  Score
    0     Team One       23    NaN
    1     Team Two       102   NaN
    2     Team Three     44    NaN
    3     Team Four      40    NaN