Reputation: 71
I just wanted to know if whether there is a way to skip the first line of a text file,by ONLY using read() to read the file and NOT readlines()
Upvotes: 2
Views: 7621
Reputation: 4035
Call next()
on the file handle:
with open('file.txt') as f_in:
next(f_in) # skip the first line
print(f_in.read())
Upvotes: 0
Reputation: 580
If you are restricted to only use read()
, you can do this in a loop, providing a size as an argument to read()
. If you reach the newline-separator '\n'
, you can exit the loop as you have reached the end of the first line.
with open('file.txt') as f:
char = f.read(1)
while char != '\n':
char = f.read(1)
Upvotes: 0
Reputation: 1994
Here is the way :)
file = open('path/file.txt','r')
lines = file.readlines()[1:] #this will skip 1st line
Upvotes: 0
Reputation: 22021
The readline is correct way of doing so, since your point is on achieving that without readline, you can do it with os.linesep:
import os
fpath = __file__
with open(fpath, 'r') as f:
candidate = None
while candidate != os.linesep:
try:
candidate = f.read(1)
print("Read a character:", candidate)
except Exception:
break
content_after_first_line = f.read()
print(content_after_first_line)
Upvotes: 0
Reputation: 13120
You'll need to iterate over the file somehow to decide when you've gotten to a line. But you can use readline
instead of readlines
to just read one line, not all lines, from the file. That's almost certainly what you want:
fd = open('file.txt')
first_line = fd.readline() #
rest_of_file = fd.read() # All but the first line
Notice it's not plural. readline
instead of readlines
Upvotes: 3