我想读取我创建的CSV文件,并将其打印在新行上:
这是代码
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)
我得到的输出是。。。
['TeamName', 'MCount']
[[], ['team One', '23'], ['Team Two', '102'], ['Team Three', '44'], ['Team Four', '40']]
我希望它看起来像这样:
Team One 23
Team Two 102
Team Three 44
Team Four 40
您可以迭代您的行,并以您想要的格式打印每一行:
# For each row
for row in rows:
# Make sure the row is not empty
if row:
# Print the row
print(row[0], row[1])
或者,您可以使用列表理解将其全部保存为变量的字符串:
# 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])
此方法将以您请求的格式打印,并为您的行编号。
import pandas as pd
data = pd.read_csv('test.csv', header = None, names = ['Team Name', 'Number', 'Score'])
print(data)
输出:
Team Name Number Score
0 Team One 23 NaN
1 Team Two 102 NaN
2 Team Three 44 NaN
3 Team Four 40 NaN
现在有最后一个问题;
这是输出:
''
0 1 2
0 TeamName MCount得分
1 Team One 23 NaN
2第二组234 NaN
3第三组3 NaN
''
上面的数字我不想要