简体   繁体   中英

Read csv file in python

My file.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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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