我正在编写一个脚本来将文本文件解析为自己的电子表格,为此我需要通读它们。问题是找出何时停止。Java在阅读时附加了一个方法调用hasNext()
,或者hasNextLine()
我想知道Python中是否有类似的方法?由于某种原因我在任何地方都找不到这个。
前任:
open(f) as file:
file.readline()
nextLine = true
while nextLine:
file.readline()
Do stuff
if not file.hasNextLine():
nextLine = false
Run Code Online (Sandbox Code Playgroud)
只需使用 for 循环来迭代文件对象:
for line in file:
#do stuff..
Run Code Online (Sandbox Code Playgroud)
\n
请注意,这包括每个字符串末尾的新行字符 ( ) line
。这可以通过以下任一方式删除:
for line in file:
line = line[:-1]
#do stuff...
Run Code Online (Sandbox Code Playgroud)
或者:
for line in (l[:-1] for l in file):
#do stuff...
Run Code Online (Sandbox Code Playgroud)
您只能通过读取来检查文件是否还有另一行(尽管您可以在不进行任何读取的情况下检查是否位于文件末尾file.tell
)。
file.readline
这可以通过调用并检查字符串是否不为空或timgeb 的调用next
并捕获异常的方法来完成StopIteration
。
因此,要准确回答您的问题,您可以通过以下方式检查文件是否还有另一行:
next_line = file.readline():
if next_line:
#has next line, do whatever...
Run Code Online (Sandbox Code Playgroud)
或者,不修改当前文件指针:
def has_another_line(file):
cur_pos = file.tell()
does_it = bool(file.readline())
file.seek(cur_pos)
return does_it
Run Code Online (Sandbox Code Playgroud)
它重置文件指针,将文件对象重置回其原始状态。
例如
$ printf "hello\nthere\nwhat\nis\nup\n" > f.txt
$ python -q
>>> f = open('f.txt')
>>> def has_another_line(file):
... cur_pos = file.tell()
... does_it = bool(file.readline())
... file.seek(cur_pos)
... return does_it
...
>>> has_another_line(f)
True
>>> f.readline()
'hello\n'
Run Code Online (Sandbox Code Playgroud)
我用于读取文本文件的典型节奏是这样的:
with open('myfile.txt', 'r') as myfile:
lines = myfile.readlines()
for line in lines:
if 'this' in line: #Your criteria here to skip lines
continue
#Do something here
Run Code Online (Sandbox Code Playgroud)
使用with
只会使文件保持打开状态,直到执行完其块中的所有代码为止,然后文件将被关闭。我还认为在这里强调该readlines()
方法很有价值,该方法读取文件中的所有行并将它们存储在列表中。在处理换行符 ( ) 字符方面\n
,我会向您指出@Joe Iddon 的答案。