python - 使用新行读取 csv 文件

标签 python csv newline readfile

我想读取我创建的 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/

相关文章:

linux - 使用变音符号导出 CSV 会导致输出中出现奇怪的字符

python - 无法使用 buildozer 构建 apk

python - Django 代码更改未反射(reflect)在生产服务器上

python - ENTER 按键使用 Selenium WebDriver 和 python

python - 对 csv 读取分割一切感到困惑

c - Sscanf 读取一行两次?

python - pickle.load() 在 Windows 中引发 EOFError

java - 如何将换行符从我的 Servlet 传递给 JavaScript?

android - 从 Kotlin android 中的 json 字符串中删除换行符\n

python - 在numpy中获得matrix < matrix结果的最快方法是什么?