如何存储可迭代文件的当前行?显然Python不支持内联赋值
f = open('parseMe.txt', 'r')
iroFile = iter(f)
while("\\" in (curLine = next(iroFile))):
print curLine
我甚至尝试了以下方法:但我仍然遇到语法错误。
while((curLine = next(iroFile)):
if ("\\" in curLine):
print curLine
答案 0 :(得分:1)
在Python中,赋值是一个语句,而不是表达式 - 但如果你习惯了Python习语,我怀疑你会想念它。
这里有一些你想要寻找的东西:
#!/usr/local/cpython-2.7/bin/python
with open('parseMe.txt', 'r') as file_:
for curLine in file_:
if '\\' not in curLine:
break
print curLine.rstrip('\n')
答案 1 :(得分:0)
文件是可迭代的,因此您应该使用for
循环:
f = open('parseMe.txt', 'r')
for line in f:
if '\\' in line:
print line
答案 2 :(得分:0)
Python file
对象可以逐行迭代,所以这是最简单的方法:
for curLine in open('parseMe.txt', 'r'):
if "\\" in curLine:
print curLine
答案 3 :(得分:0)
你缺少一个大括号
while((curLine = next(iroFile)):
最外面的牙箍也不是必需的。
此代码应该执行相同的操作
print "".join([x for x in open("x.txt") if '\\' in x])
或
import sys
[sys.stdout.write(x) for x in open("x.txt") if '\\' in x]
或
import sys
if sys.version_info.major < 3:
from __future__ import print_function
[print(x) for x in open("x.txt") if '\\' in x]