使用新行读取 csv 文件
Reading csv files with new lines
我想读取我创建的 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 队一 23 NaN
2 二队 234 NaN
3 三队 3 NaN
'''
我不想要上面的数字
我想读取我创建的 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 队一 23 NaN
2 二队 234 NaN
3 三队 3 NaN
'''
我不想要上面的数字