我想读取我创建的 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])
关于python - 使用新行读取 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71649026/