【发布时间】:2018-03-25 22:58:23
【问题描述】:
我目前有一个正在读取的文本文件,其中包含 6 个我需要能够单独呼叫的号码。
文本文件如下所示
11 12 13
21 22 23
到目前为止,我已经使用以下方法尝试获得正确的输出,但没有成功。
with open(os.path.join(path,"config.txt"),"r") as config:
mylist = config.read().splitlines()
print mylist
这给了我 ['11 12 13', '21 22 23']。
with open(os.path.join(path,"config.txt"),"r") as config:
contents = config.read()
params = re.findall("\d+", contents)
print params
这给了我 ['11', '12', '13', '21', '22', '23']
with open(os.path.join(path,"config.txt"),"r") as config:
for line in config:
numbers_float = map(float, line.split())
print numbers_float[0]
这给了我 11.0 21.0
最后一种方法是最接近的,但在第一列中给了我两个数字,而不仅仅是一个。
我也可以用逗号分隔文本文件中的数字,结果相同或更好吗?
感谢您的帮助!
【问题讨论】:
-
你想要的输出到底是什么?另外,为什么你标记了这个
int,但在你的代码中使用了float?你想要哪一个?cloud9标签有什么相关性?
标签: python string text int cloud9