[英]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.