刚刚开始学习Python,我正在努力解决这个问题。
我正在打开一个长度可变的txt文件,我需要一次迭代用户可定义的行数。当我到达文件的末尾时,我在主题字段中收到错误。我还尝试了readlines()函数和导致问题的“if”语句的几个变体。我似乎无法获得代码来找到EOF。
嗯,当我写这篇文章时,我在想......我是否需要将数据库“EOF”添加到数组中并且只是寻找它?这是找到自定义EOF的最佳解决方案吗?我的代码段如下:
### variables defined outside of scapy PacketHandler ##
x = 0
B = 0
##########
with open('dict.txt') as f:
lines = list(f)
global x
global B
B = B + int(sys.argv[3])
while x <= B:
while y <= int(sys.argv[2]):
if lines[x] != "":
#...do stuff...
# Scapy send packet Dot11Elt(ID="SSID",info"%s" % (lines[x].strip())
# ....more code...
x = x 1
答案 0 :(得分:0)
尝试for循环。您已经创建了列表,现在可以遍历它。
with open('dict.txt') as f:
lines = list(f)
for item in lines: #each item here is an item in the list you created
print(item)
通过这种方式,您可以浏览文本文件的每一行,而不必担心它的结束位置。
编辑:
你也可以这样做!
with open('dict.txt') as f:
for row in f:
print(row)
答案 1 :(得分:0)
假设您需要一次读取X行,将其放入列表并进行处理:
with open('dict.txt') as f:
enoughLines = True
while enoughLines:
lines = []
for i in range(X):
l = f.readline()
if l != '':
lines.append( l )
else:
enoughLines = False
break
if enoughLines:
#Do what has to be done with the list “lines”
else:
break
#Do what needs to be done with the list “lines” that has less than X lines in it
答案 2 :(得分:0)
以下函数将返回一个生成器,该生成器返回文件中的下n行:
def iter_n(obj, n):
iterator = iter(obj)
while True:
result = []
try:
while len(result) < n:
result.append(next(iterator))
except StopIteration:
if len(result) == 0:
raise
yield result
以下是如何使用它:
>>> with open('test.txt') as f:
... for three_lines in iter_n(f, 3):
... print three_lines
...
['first line\n', 'second line\n', 'third line\n']
['fourth line\n', 'fifth line\n', 'sixth line\n']
['seventh line\n']
test.txt的内容:
first line
second line
third line
fourth line
fifth line
sixth line
seventh line
请注意,因为文件没有3行的倍数,所返回的最后一个值不是3行,而是文件的其余部分。
因为此解决方案使用生成器,所以不要求将完整文件读入内存(放入列表中),而是根据需要对其进行迭代。
实际上,上面的函数可以迭代任何可迭代对象,如列表,字符串等:
>>> for three_numbers in iter_n([1, 2, 3, 4, 5, 6, 7], 3):
... print three_numbers
...
[1, 2, 3]
[4, 5, 6]
[7]
>>> for three_chars in iter_n("1234567", 3):
... print three_chars
...
['1', '2', '3']
['4', '5', '6']
['7']
答案 3 :(得分:0)
如果你想在列表中获得n行,请使用itertools.islice产生每个列表:
from itertools import islice
def yield_lists(f,n):
with open(f) as f:
for sli in iter(lambda : list(islice(f,n)),[]):
yield sli
如果你想使用循环,你根本不需要一个while循环,你可以使用范围n-1中的内循环调用文件对象的下一个,默认值为空字符串,如果我们得到的话一个空字符串打破循环,如果不只是追加并再次产生每个列表:
def yield_lists(f,n):
with open(f) as f:
for line in f:
temp = [line]
for i in range(n-1):
line = next(f,"")
if not line:
break
temp.append(line)
yield temp