2014-11-05 56 views
-3

我已经使用python创建了文件,我需要比较它。我如何使用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

你能不能给你有文件数据? – jack 2014-11-05 06:27:58

+0

我编辑了这个问题 – Kelly 2014-11-05 06:37:37

回答

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 

你也许应该这样做数学上的绳子。并且您没有在文件中保存用户名,您应该如何比较数据,而无需了解某个事件中谁在哪个时间点的信息?

你可能会写下你正在尝试做的事情,那么我们可以帮助你更好吗?

+0

我现在编辑了这个问题,我在比较 – Kelly 2014-11-05 06:39:04

+0

文件中的信息好,但是仍然有缺失的信息。在我的答案中阅读我的编辑。也许告诉我们你想做什么,如果你想比较你也应该保存关于谁有什么时间的信息。有多种方式可以做到这一点,您首先应该考虑如何存储信息,以便于阅读。 – eivl 2014-11-05 08:37:10

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...