【发布时间】:2019-09-06 19:40:29
【问题描述】:
假设我有一个文件my_file,我想要其中的某些行,例如其中每一行输出都是一个列表元素。我试图了解如何控制和使用 Python 文件 i/o 操作。
文件:
cat > my_file <<EOF
[Ignore_these]
abc
234
[Wow]
123
321
def
[Take_rest]
ghi
jkl
EOF
说,在 [Wow] 行之后,我想合并整数行(可以是任意数量的行,这里我得到 '123321')并忽略其余部分,直到我遇到我想要剩余行的 [Take_rest] ('ghi' and 'jkl')- [Take_rest] 始终是最后一部分。所以结果输出是data = list('123321', 'ghi', 'jkl')。
我尝试了类似以下的方法,但无法理解 readline() 和 next() (etc) 的工作原理。
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
with open('my_file', 'r') as f:
data = []
while True:
line = f.readline()
if '[Wow]' in line:
wow = ''
while is_int(next(f)):
wow = ''.join([wow, line])
data.append(wow)
if '[Take_rest]' in line:
data.append(next(f))
if not line:
break
【问题讨论】:
-
[Take_rest]会一直是最后一个部分吗? -
是的 - (好点)
标签: python file io readline next