[英]Trying to Figure out how to properly use a while loop in Python 3.3.0
[英]trying to figure out how to get the next values using a loop in python
我正在尋找一些資源,我的代碼打印了兩個 txt 文件之間的第一個不相等的值。 我想要做的是如果我按下一個鍵,如何獲得下一個不相等的值。 我認為 while 循環會有所幫助,但我在每個邏輯上都失敗了。 任何我可以找到答案的資源?
def textdiff():
text1 = open("text1.txt", "r")
text2 = open("text2.txt", "r")
for orgtext1 in text2:
for oldtext2 in text1:
if oldtext2 != orgtext1:
return oldtext2
text1.close()
text2.close()
print(textdiff())
多謝
如果要將文件 1 的第 n 個字符與文件 2 的第 n 個字符進行比較,我將使用yield
在每個發現不等式和with
語句后跳出函數,以確保在出現錯誤時正確關閉文件提高:
def textdiff():
with open("text1.txt", "r") as file1:
with open("text2.txt", "r") as file2:
text1 = file1.read()
text2 = file2.read()
shared_length = min(len(text1), len(text2))
for pos in range(shared_length):
if text1[pos] != text2[pos]:
yield text1[pos] + " != " + text2[pos]
for diff in textdiff():
print(diff)
input('Press <Return> to continue')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.