我使用python创建了文件,我需要进行比较。如何使用python比较这两个文件?
def td():
choice = input("which trainning event would you like to access?
\n1.swimming
\n2.cycling
\n3.running\nplease type in the number before the event of which you want to choose\n")
if choice == "1":
Swimming_file= open("Swimming_file.txt", "w")
totaldistance = input("what was the total distance you swam in meters?")
totaltime = input("how long did you swim for in minutes?")
speed = totaldistance/totaltime
print ("on average you where running at a speed of", speed, "mps")
total = (totaldistance, totaltime, speed)
Swimming_file.write(str(total))
Swimming_file.close()
elif choice == "3":
Running_file= open("Running_file.txt", "w")
totaldistanceR = int(input("what was the total distance you ran in KM?"))
totaltimeR = int(input("how long did you run for in minutes?"))
totaltimeR1 = 60/totaltimeR
speedR1 = totaldistanceR/totaltimeR1
print ("The records have been saved")
print ("on average you where running at a speed of", speedR1, "KMph")
totalR = (totaldistanceR, totaltimeR, speedR1)
Running_file.write(str(totalR))
Running_file.close()
elif choice == "2":
Cycling_file= open("Cycling_file.txt", "w")
totaldistancec = int(input("what was the total distance you ran in KM?"))
totaltimec = int(input("how long did you run for in minutes?"))
speedc = totaldistancec/totaltimec
print ("on average you where running at a speed of", speedc, "KMph")
totalc = (totaldistancec, totaltimec, speedc)
Cycling_file.write(str(totalc))
Cycling_file.close()
创建的文件包含以用户名命名的运行时间。我需要比较文件,以便用户可以看到其他用户的速度。
我一直在网上寻找这个解决方案,但没有一个与我的问题相关。
答案 0 :(得分:0)
我认为您首先需要更新您的问题。如果您想比较两个文件,可以这样做:
from __future__ import with_statement
with open(filename1) as f1:
with open(filename2) as f2:
if f1.read() == f2.read():
...
或者这样
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
...
但是你没有说清楚你想要什么,你究竟在比较什么,你是否将文件内的信息与不同的用户名和时间进行比较?文件是如何构建的。您是否需要先选择一个用户,然后找到按时间排序的用户与其他用户进行比较的位置?
只要你写出优秀的描述,我们就会帮助你。
OP更新帖子后编辑:您仍需要提供有关数据的信息。你确定你的代码就像你写的那样运行,speed = totaldistance/totaltime
你可能不应该对字符串进行数学运算。并且您没有在文件中保存用户名,如何在没有关于谁在某个事件中有什么时间的信息的情况下比较数据?
你可以写下你想做的事情,这样我们可以帮助你更好吗?答案 1 :(得分:0)
我不确定你的问题,但我认为这是你的答案:
U1 = open('file1.txt', 'r')
U2 = open('file2.txt', 'r')
username1 = U1.readline()
username2 = U2.readline()
if U1.readline() >= U2.readline():
#do something
else:
#do something else...