nqtuan87
nqtuan87

Reputation: 3

Import csv file (a line of string)

Here my csv file content:

'GK', 'M', 'A', 'D', 'M', 'D', 'M', 'M'

I try to import the csv file to python program as a list of string as:

['GK', 'M', 'A', 'D', 'M', 'D', 'M', 'M']

However through csv.reader it returns a list of list and contains only one string as:

["'GK', 'M', 'A', 'D', 'M', 'D', 'M', 'M'"]

I tried to figure out the solution, but it took too many steps as follows:

import csv
filepath = 'positions copy.csv'
file = open(filepath)
data = file.read().splitlines()
print(data)
data_2 = ''.join(data)
print(data_2)
data_3 = data_2.replace("'", "").replace(" ","")
print(data_3)
positions = data_3.split(',')
print(data_4)

Any shorter solution?

Upvotes: 0

Views: 735

Answers (4)

Christian Sloper
Christian Sloper

Reputation: 7510

Here is an answer using csv-reader, it is done using some of the various optional parameters for csv-reader, you can see all of them here. Note that delimeter defaults to ',' so you don't strictly need it in your example:

import csv

with open("positions copy.csv",'rt') as f:
    print(next(csv.reader(f,delimiter = ',', quotechar = "'", skipinitialspace = True)))

Upvotes: 4

JPI93
JPI93

Reputation: 1557

Given a file in the current directory (data.csv) with the following contents:

'GK', 'M', 'A', 'D', 'M', 'D', 'M', 'M'

The following code will:

  1. Read the contents from the file to the data variable
  2. Split the data string into a list of strings, delimited by the character sequence ,
  3. Remove any instances of the character ' from each list item
  4. Strip any leading/trailing white-space from each list item
with open('data.csv', 'r') as f:
     data = f.read()

data = [ s.replace('\'', '').strip() for s in data.split(', ') ]

The result is a list of strings (data) that looks like this when print(data) is called:

['GK', 'M', 'A', 'D', 'M', 'D', 'M', 'M']

Upvotes: 0

use 'pandas' module.

import pandas as pd
file=pd.read_csv('Your File')

now the file is pandas DataFrame but if you want numpy ndarray add this:

file=file.values

Upvotes: 0

Deepak Tripathi
Deepak Tripathi

Reputation: 3243

use this

with open('file1.txt',encoding='utf-8') as data:
    print(data.read().strip().strip('"'))

Upvotes: 0

Related Questions