在python中读取csv文件

时间:2019-09-25 10:06:16

标签: python python-3.x list

我的file.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']']

我应该添加什么才能获得所需的阵列?

4 个答案:

答案 0 :(得分:2)

您无需为此使用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]

答案 1 :(得分:1)

import csv

data = []
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']

答案 2 :(得分:1)

您可以将代码更改为

import csv

data = []
with open('file.csv', 'r') as f:
  reader = csv.reader(f)
  for row in reader:
    [row] = row
    data.append(f"str-{row}")

答案 3 :(得分:0)

您可以考虑使用pandas来读取csv文件,而不是一行一行地读取,然后在列的每个元素上添加前缀,如下所示:

import pandas as pd
df = pd.read_csv("file.csv", names=["col_0"])
data = ("str-" + df["col_0"].astype(str)).tolist()