Home > Software design >  How to read content of txt file the values are comma separated and add it to a list?
How to read content of txt file the values are comma separated and add it to a list?

Time:05-24

I have a file that contains the following content. This is a sample of the file. The fine contains up to 1000 values.

'1022409', '10856967', '11665741'

I need to read the file and create this list ['1022409', '10856967', '11665741']

I'm using the following code:

with open('Pafos.txt', 'r') as f:
    parcelIds_list = f.readlines()
    print (parcelIds_list[0].split(','))

The value is of parcelIds_list parameter is this list ["'1022409', '10856967', '11665741'"] with only index 0.

Any ideas please?

CodePudding user response:

Follow this code

with open ('Pafos.txt', 'r') as f:
  # To split 
  num = f.readline().split(', ')
  # To remove ' and create list
  # If u want list of string
  num_list = [x.replace('\'', '') for x in num]

Output

['1022409', '10856967', '11665741']

If u want list of int

# If u want list of int
num_list = [int(x.replace('\'', '')) for x in num]

Output

[1022409, 10856967, 11665741]

If u have more than one row in file, you need to add some extra line of code

CodePudding user response:

It is a bit hard to code with the few lines you have given from the text file, but try this :

temp = []
with open('Pafos.txt', 'r') as f:
    parcelIds_list = f.readlines()
    for j in parcelIDS_list:
         temp.extend(j.split(", "))
    new_list = [i.strip()[1:-1] for i in temp]
    print(new_list)
    

Let me know if this doesn't work, and what went wrong. I will modify my answer likewise.

CodePudding user response:

I found the solution thanks to this.

with open('Pafos.txt', 'r') as f:
    parcelIds_list = f.readlines()
    cs_mylist = []
    for y in [x.split(',') for x in parcelIds_list]:
        for z in y:
            cs_mylist.append(z.replace(' ', ''))

CodePudding user response:

Probably there is a cleaner way, but this works:

with open('Pafos.txt', 'r') as f:
    parcelIds_list = f.readlines()
    line = parcelIds_list[0]
    line = line.replace("'", "")
    line = line.replace(" ", "")
    line = line.split(',')
    print(line)
  • Related