将CSV导入转换为字符串

时间:2017-12-08 22:20:09

标签: python python-3.x csv

我有一个脚本:

import csv

with open('2017020397.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(' '.join(row))

输出如下:

LastName StartTime EndTime Duration Period TeamAbbrev Pos
Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D

我希望行与数据相等,而不是打印行。然后我可以说print(data)。 python和编写脚本的新手。

1 个答案:

答案 0 :(得分:3)

这样做:

import csv

with open('2017020397.csv', newline='') as f:
    data = '\n'.join(' '.join(row) for row in csv.reader(f))

print(data)

输出:

LastName StartTime EndTime Duration Period TeamAbbrev Pos
Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D

为了保留标题,您需要稍微改变一下:

with open('2017020397.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader)  # Skip header row.
    data = '\n'.join(' '.join(row) for row in reader)

print(data)

输出忽略标题:

Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D