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
CodePudding user response:
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
CodePudding user response:
You can iterate over your rows and print each row in the format that you'd like:
# For each row
for row in rows:
# Make sure the row is not empty
if row:
# Print the row
print(row[0], row[1])
Or alternatively, you could use list comprehension to save it all as a string to a variable:
# For each row,
# if the row is not empty
# format it into a string.
# Join all the resulting strings together by a new line.
my_data_string = "\n".join([f"{row[0]} {row[1]}" for row in rows if row])
CodePudding user response:
Now have one final problem;
this is the output:
'''
0 1 2
0 TeamName MCount Score
1 Team One 23 NaN
2 Team Two 234 NaN
3 Team Three 3 NaN
'''
the numbers on top i do not want