[英]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)
我得到的 output 是這個...
['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)
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
現在有最后一個問題;
這是 output:
'''
0 1 2
0 TeamName MCount 分數
1 團隊一 23 NaN
2 二隊 234 NaN
3 三隊 3 NaN
'''
我不想要上面的數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.