0

我有一个这样的txt文件:

2,5,25,6
3,5,78,6,
5,23,24,85
6,4,79,9
69,23,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 文件中存在的所有行。

4

3 回答 3

0

与索引一起使用.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])
于 2020-11-09T10:37:43.200 回答
0

通过 iostream 打开文件后,您可以使用readlines()将整个数据传输到列表中。并且您可以通过列表的索引获得您想要的值。

with open("value.txt", "r") as fp:
    lines = fp.readlines()
    first = lines[0].split(',')[0]
    end = lines[-1].split(',')[0]

    print(first, end)
于 2020-11-09T10:40:24.693 回答
0

类似于下面的东西

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
于 2020-11-09T10:45:43.293 回答