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()
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 readline s
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)
Here is the way:)
file = open('path/file.txt','r')
lines = file.readlines()[1:] #this will skip 1st line
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)
Call next()
on the file handle:
with open('file.txt') as f_in:
next(f_in) # skip the first line
print(f_in.read())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.