Reputation: 3
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
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
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:
data
variabledata
string into a list of strings, delimited by the character sequence ,
'
from each list itemwith 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
Reputation: 307
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
Reputation: 3243
use this
with open('file1.txt',encoding='utf-8') as data:
print(data.read().strip().strip('"'))
Upvotes: 0