在python中读取csv文件

我的文件.csv:


1

2

3

7

我需要将此文件转换为如下列表:


['str-1', 'str-2', 'str-3', 'str-7']


为此,我做了:


import csv


data = []

with open('file.csv', 'r') as f:

  reader = csv.reader(f)

  for row in reader:

    data.append(f"str-{row}")

当我看到这行的结果时,我得到了:


['str-['1']', 'str-['2']', 'str-['3']', 'str-['7']']


我应该添加什么来获得我需要的数组?


ibeautiful
浏览 114回答 3
3回答

杨魅力

您不需要为此使用csv:data = []with open('file.csv') as f:    for row in f:        data.append(f"str-{row.strip()}")或作为列表理解:with open('file.csv') as f:    data = [f"str-{row.strip()}" for row in f]

狐的传说

import csvdata = []with open('file.csv', 'r') as f:    reader = csv.reader(f)    for row in reader:        data.append("str-"+row[0])print(data)>> ['str-1', 'str-2', 'str-3', 'str-7']

ABOUTYOU

您可以将代码更改为import csvdata = []with open('file.csv', 'r') as f:  reader = csv.reader(f)  for row in reader:    [row] = row    data.append(f"str-{row}")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python