第一次只移动 zip Python 中两个迭代器中的一个
Move only 1 of two iterators in zip Python the first time
我正在阅读两个文本文件并想一起遍历它们。但是其中一个在我想跳过的第一行有 headers。如果我在看到 header 行后 'continue' ,两个迭代器都向前移动,并且我想在文件中比较的数据不再对齐。
我该怎么做才能跳过其中一个文件的第一行,然后开始遍历这两个文件?
with open('path/to/file/without/headers') as file1, open('path/to/file/with/headers') as file2:
file2.readline()
answer = zip(file1, file2)
通常,您希望在 传递给 zip
之前 推进迭代器。您可以使用 next
内置函数执行此操作:
header = next(file1)
for line1, line2 in zip(file1, file2):
...
您可以使用文件 object 的 seek
方法移动到特定行:
http://www.tutorialspoint.com/python/file_seek.htm
例如:
for f in (file1, file2):
if not is_header(f.readline()):
f.seek(0)
lines = zip(file1, file2)
只需将 is_header
替换为某些检查以定义该行是 header。在这种情况下,如果第一行是 header,则此文件的迭代器将位于第二个位置,否则它将位于第一个位置,因为我们调用 seek
位置为 0.
的方法
我正在阅读两个文本文件并想一起遍历它们。但是其中一个在我想跳过的第一行有 headers。如果我在看到 header 行后 'continue' ,两个迭代器都向前移动,并且我想在文件中比较的数据不再对齐。
我该怎么做才能跳过其中一个文件的第一行,然后开始遍历这两个文件?
with open('path/to/file/without/headers') as file1, open('path/to/file/with/headers') as file2:
file2.readline()
answer = zip(file1, file2)
通常,您希望在 传递给 zip
之前 推进迭代器。您可以使用 next
内置函数执行此操作:
header = next(file1)
for line1, line2 in zip(file1, file2):
...
您可以使用文件 object 的 seek
方法移动到特定行:
http://www.tutorialspoint.com/python/file_seek.htm
例如:
for f in (file1, file2):
if not is_header(f.readline()):
f.seek(0)
lines = zip(file1, file2)
只需将 is_header
替换为某些检查以定义该行是 header。在这种情况下,如果第一行是 header,则此文件的迭代器将位于第二个位置,否则它将位于第一个位置,因为我们调用 seek
位置为 0.