如何解决如何在python中从txt文件中提取第一个和最后一个值?
我有一个这样的txt文件:
2,5,25,6
3,78,6,23,24,85
6,4,79,9
69,12,51
我应该只提取两个值,它们是第一行2中的第一个值和最后一行69中的第一个值。 我编写的程序如下:
with open("C:\values.txt","r") as fp:
lines = fp.readlines()
for i in range(0,len(lines)):
print(lines[i])
但是我只能打印txt文件中存在的所有行。
解决方法
与.read()
一起使用索引:
with open(r"C:\values.txt","r") as fp:
txt = fp.read().strip()
first_val = int(txt.split("\n")[0].split(",")[0])
last_val = int(txt.split("\n")[-1].split(",")[0])
,
通过iostream打开文件后,可以使用TypeError: Cannot read property 'appendChild' of null
将整个数据传输到列表中。然后,您可以通过列表的索引获取所需的值。
readlines()
,
类似以下内容
with open("values.txt","r") as fp:
lines = [l.strip() for l in fp.readlines()]
first_and_last = [lines[0],lines[-1]]
for l in first_and_last:
print(l.split(',')[0])
输出
2
69
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。