Peter
Peter

Reputation: 1

Splitting a string into separate values when one part contains comma between quotationmarks (Python)

First of all, I'm a newbee at python.

I read data from a file on harddrive, no problem there. It's when using split() my problem occur. Example of how a line looks like in the original file:

0,0,1,5,20,"Good for you, Helen."

The problem is the comma between the quotationmarks. strip() thinks it is two separate values. I want the text between the quotes to be intact and copied to 'name'. How do I tell split() not to react to the comma between quotes (as a separator) and instead copy all characters between the qutes 'as is'? I can not make changes to the original file, because I don't create it.

The error I get when running the code: "ValueError: too many values to unpack (expected 6)", which is understandable...

filename="data.txt"
file = open(filename, 'r')
  for line in file:
     readroom = line.strip()
     a,y,f, thig, wam, name = line.split(",",6)
     thig = int(thig.strip())
     name = name.strip()
     wam = int(wam.strip())

Upvotes: 0

Views: 64

Answers (2)

Alif Jahan
Alif Jahan

Reputation: 795

You can try something like this,

filename="data.txt"
file = open(filename, 'r')
for line in file:
    readroom = line.strip() 
    listOfValue = line.split(",")
    if len(listOfValue) > 6:
        listOfValue[5] = ','.join(listOfValue[-2:])
    listOfValue = listOfValue[:6]
    # now all the values in order
    a,y,f, thig, wam, name = listOfValue
    thig = int(thig.strip())
    name = name.strip()
    wam = int(wam.strip())

At first split with comma then set the 5th index if there is more than 6 element and join with a ','

Upvotes: 0

Pythonista
Pythonista

Reputation: 11615

from csv import reader
for line in reader(file):
    print(line)

Upvotes: 2

Related Questions