Joel Banks
Joel Banks

Reputation: 151

How to group values together when reading from a file in python

I'm trying to redo old code for one of my projects, and I'm going to start with reading the list of values from a file instead of hardcoding it in. My python code looks like

f=open("readtimes.txt", "r")
if f.mode == 'r':
    contents = f.read()
    print(list(contents))

and for simplicity lets say readtimes.txt is filled with "12.345, 23.456, 34.567"

The problem is when I print the list, it comes out as

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

and so on. How do I get it to print

['12.345', '23.456', '34.567']'

Thanks for the help!

Upvotes: 0

Views: 383

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

Building on @JacobIRR comment and taking into account the whitespaces, you could do the following:

content = "12.345, 23.456, 34.567"
result = [s.strip() for s in content.split(",")]
print(result)

Output

['12.345', '23.456', '34.567']

Or as an alternative:

content = "12.345, 23.456, 34.567"
result = list(map(str.strip, content.split(",")))
print(result)

Output

['12.345', '23.456', '34.567']

Upvotes: 2

Related Questions