Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading