-1

I have a txt file made like this:

2,5,25,6
3,5,78,6,
5,23,24,85
6,4,79,9
69,23,12,51

I should extract only two values that are the first value in the first line 2 and the first value in the last line 69. The program I wrote is the following:

with open("C:\values.txt", "r") as fp:
    lines = fp.readlines()
for i in range(0, len(lines)):
    print(lines[i])

but I can only print all the lines present in the txt file.

luna8899
  • 55
  • 5
  • 1
    Note, there is basically never a good reason to use `readlines`, it's a relic. File objects are iterators, your code could just be `for line in fp: print(line)` – juanpa.arrivillaga Nov 09 '20 at 10:32
  • And after being able to access each line in the for loop; then what is the next step? You could start to look at the lines[i] type and notice it's a string and not (yet) a list of numbers. Then how do you convert this string into a list of numbers? And finally, access the first number on the first line and the last number on the last line. – Mathieu Nov 09 '20 at 10:32
  • as output I need : 2, 69 – luna8899 Nov 09 '20 at 10:36

3 Answers3

0

Use indexing along with .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])
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

After opening the file via iostream, you can use readlines() to transfer the whole data to the list. And you can get the value you want with the index of the list.

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

    print(first, end)
Jet C.
  • 126
  • 8
0

something like the below

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])

output

2
69
balderman
  • 22,927
  • 7
  • 34
  • 52