[英]how to skip first line in python using read() function?
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()我只是想知道是否有办法跳过文本文件的第一行,仅使用 read() 读取文件而不是 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.但是您可以使用
readline
而不是readlines
从文件中读取一行,而不是所有行。 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 readline
而不是 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 : readline 是这样做的正确方法,因为您的观点是在没有 readline 的情况下实现这一点,您可以使用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()
.如果您仅限于使用
read()
,则可以在循环中执行此操作,将大小作为参数提供给read()
。 If you reach the newline-separator '\n'
, you can exit the loop as you have reached the end of the first line.如果到达换行符
'\n'
,则可以在到达第一行末尾时退出循环。
with open('file.txt') as f:
char = f.read(1)
while char != '\n':
char = f.read(1)
Call next()
on the file handle:在文件句柄上调用
next()
:
with open('file.txt') as f_in:
next(f_in) # skip the first line
print(f_in.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.