-1

i would like to know how i could get all lines after the first in a python file

I've tried with this:

fr = open("numeri.txt", "r")

count = 0
while True:
    line = fr.readline(count)
    if line == "":
        break
    count += 1
    print(line)
fr.close()

Could anyone help me? Thanks

mAndAle
  • 17
  • 3

7 Answers7

0

You could add an extra if statement to check if count != 0 Since on the first loop it will be 0.

xl3ehindTim
  • 121
  • 1
  • 7
0

I don't know if i understood well, but to obtain all the lines skipping the first one you can simple do

lines = []
with open("numeri.txt") as fobj:
   lines = fobj.readlines()[1:] 
count = len(lines)+1 if lines else 0 # If you want to maintain the same counting as in your example
Cristian
  • 119
  • 3
0

Just read the first line without using it:

with open('numeri.txt') as f:
    f.readline()
    lines = f.readlines()
print(*lines, sep='')

To ignore the first line you can also use next(f) (instead of f.readline()).

This is also fine:

with open('numeri.txt') as f:
    lines = f.readlines()[1:]
print(*lines, sep='')
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
0
count = 0
with open(file, 'r') as file:
    next(file.readline())  # skip the first line
    for count, line in enumerate(file.readlines()): # read remaining lines with count
        if not line:  # If line equals ""  this will be True
            break
        print(count, line)
  
count -= 1 # To ignore last lines count. 
Thymen
  • 2,089
  • 1
  • 9
  • 13
0

Try using l[1:]. It returns a subset of l that consist in the elements of l except the first position.

with open("numeri.txt", "r") as f:
    content = f.readlines()[1:]
for line in content:
    print(line.strip('\n')) # In order to avoid introduce double \n since print ends with a '\n'

EDIT: Based on @riccardo-bucco ' solution:

with open("numeri.txt", "r") as f:
    content = f.readlines()[1:]
    print(*content, sep='')
Keredu
  • 378
  • 1
  • 14
0

To print all but the first line:

with open('numeri.txt', 'r') as f:
    output = ''.join(f.readlines()[1:])
    print(output)
H S
  • 45
  • 4
-1

start count at 1 so it skips the first line

...
count = 1
...
Hadrian
  • 917
  • 5
  • 10