简体   繁体   English

读取 python 中的 csv 文件

[英]Read csv file in python

My file.csv:我的文件.csv:

1
2
3
7

I need to convert this file to list like:我需要将此文件转换为如下列表:

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

For this I have done:为此,我做了:

import csv

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

When I see the result of this lines I got:当我看到这行的结果时,我得到了:

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

What should I add to get the array that I need?我应该添加什么来获得我需要的数组?

You don't need to use csv for this:您不需要为此使用csv

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

Or as a list comprehension:或作为列表理解:

with open('file.csv') as f:
    data = [f"str-{row.strip()}" for row in f]
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']

You can change your code to您可以将代码更改为

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}")

You can consider using pandas to read csv file instead of reading line by line followed by adding a prefix to each element of a column as folows:您可以考虑使用pandas来读取csv文件,而不是逐行读取,然后为列的每个元素添加前缀,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM