read in text file of numbers to a list without the single quotes Python

Viewed 427

When I read in a text file of numbers:

1, 2, 3, 4, 5, 6, 7, 8

The list is created like:

dTags = ['1, 2, 3, 4, 5, 6, 7, 8']

I do not want the single quotes at the beginning and end of the list, so I just want it to be like:

dTags = [1, 2, 3, 4, 5, 6, 7, 8]

This is the code I am using:

dTags = []
with open("tagNumbersToTest.txt") as file:
    for line in file: 
        line = line.strip() #or some other preprocessing
        dTags.append(line) #storing everything in memory!

#print(dTags)

How can I achieve this?

4 Answers

If you have a line:

line = "1, 2, 3, 4, 5, 6, 7, 8"

you can append a list of integers using:

dTags.append([int(x) for x in line.split(",")])

This will append a list such as:

[1, 2, 3, 4, 5, 6, 7, 8]

Then your dTags will be a list of lists. If instead you want all the lines concatenated as one list rather than a list of lists, then use extend instead of append.

In your case, it is appending a single item to a list. Your desired output contains 5 elements. One thing that you can try is -

dTags = []
with open("tagNumbersToTest.txt") as file:
    for line in file: 
        dTags.extend(line.split(','))

Output -

['1', ' 2', ' 3', ' 4', ' 5']

To get all the integer values instead of string then you can add the below line provided all the elements are of int datatype.

dTags_list = [int(i) for i in dTags]

Output -

[1, 2, 3, 4, 5]

To summarize your code -

    dTags = []
    with open("tagNumbersToTest.txt") as file:
        for line in file: 
            dTags.extend([int(i) for i in line.split(',')])

Try
(assuming you 1 line of text in your file)

with open('data.txt') as f:
  nums = [int(x) for x in f.readline().strip().split(',')]
  print(nums)

If you want to convert string to Python code, you can use eval(list(line)) even if I don't recommend it for security reasons.

dTags = []
with open("tagNumbersToTest.txt") as file:
    for line in file: 
        line = line.strip()
        dTags.append(list(eval(line)))

dTags will be a list of lists but you can then manipulate it or modify the text file to get the output you want.

https://docs.python.org/3/library/functions.html#eval

Related