如何在python中读取文件时将值组合在一起

问题描述 投票:0回答:1

我正在尝试为我的一个项目重做旧代码,我将开始从文件中读取值列表而不是硬编码。我的python代码看起来像

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

为简单起见,我们说readtimes.txt填充“12.345,23.456,34.567”

问题是当我打印列表时,它出现了

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

等等。如何打印它

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

谢谢您的帮助!

python file
1个回答
2
投票

在@JacobIRR注释的基础上并考虑到空格,您可以执行以下操作:

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

产量

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

或作为替代方案:

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

产量

['12.345', '23.456', '34.567']
© www.soinside.com 2019 - 2024. All rights reserved.