我有两个文件,如下所示:
File1:
Apple
Banana
Orange
Pineapple
File2:
Apple
Banana
Pineapple
我想同时读取两个文件,但是当我在File1中看到orange
时,我只想跳过FILE1中的那一行并转到下一行。有没有办法在python中做到这一点?
到目前为止,我已经尝试过:
with open(file1, "r") as f1, open(file2, "r") as f2:
f1_f2 = itertools.izip(f1,f2)
line1,line2 = f1_f2.next()
但是我不知道从那里去哪里。 任何帮助表示赞赏。
答案 0 :(得分:1)
是的
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
line1 = file1.readline().strip() # read line, and remove newline character at end
line2 = file1.readline().strip()
while(line1 == "Orange"):
line1 = file1.readline()
...
将此结构放入循环中-readline()
返回''
时文件为空。您也可以使用readlines()
而不是readline()
,然后根据需要遍历结果列表。
答案 1 :(得分:1)
假设文件位于当前目录中:
import os
for filename in os.listdir():
with open(filename,"r") as data:
file_contents = data.readlines()
if filename = "File1":
file_contents.remove("Orange\n")
#work with file contents
我不确定这是否是您要查找的内容,请用更多信息更新问题。
答案 2 :(得分:0)
您可以使用zip_longest
并使用next
跳过行
例如:
from itertools import zip_longest
with open(filename) as file_1, open(filename2) as file_2:
for m, n in zip_longest(file_1, file_2, fillvalue=""):
if m.strip() == "Orange":
m = next(file_1)
print(m.strip(), n.strip())
输出:
Apple Apple
Banana Banana
Pineapple Pineapple