附加到文件和消息的顺序错误python

时间:2014-10-31 11:35:07

标签: python file append

我编写了一个程序,该程序读取由10对数字组成的文件,然后将这两个数字分开,产生一个混合分数,然后将其附加到原始文档上。但是,我希望错误消息与对的顺序相同。我的文件包含:

66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 21

我的程序看起来像这样:

from fractions import gcd     
x=0
y=0
global index
index=0
wordlist=[]
with open('topheavy.txt','r') as f:
        for line in f:
            for word in line.split():
                print(word)
                wordlist.append(word)
print (wordlist)
print (len(wordlist))
def mixedfraction():
    global index
    while index<len(wordlist):
        global x
        global y
        x=wordlist[index]
        y=wordlist[index+1]
        neg=False
        with open ('topheavy.txt','a') as g:
            try:
                float(x)
            except ValueError:
                g.write ('x is not a number.\n')
                global index
                index+=2
                mixedfraction()
            try:
                float(y)
            except ValueError:
                g.write ('y is not a number.\n')
                global index
                index+=2
                mixedfraction()      
    #the above code checks if its a  number.
        x=int(x)
        y=int(y)
        orx=0
        ory=0
        orx+=x
        ory+=y
        if x==0 or y==0:
            with open ('topheavy.txt','a') as g:
                g.write ('you cant divide by 0!\n')
                global index
                index+=2
                mixedfraction()
    #this is to make sure you dont get a divide by 0 error.
        if x<0 and not y<0:
            neg=True
            x*=-1
        elif y<0 and not x<0:
            neg=True
            y*=-1
        if 1==1:
            xy=(x//y)
            modxy=(x%y)
            modxy=round(modxy,0)
            xy=round(xy,0)
            y=round(y,0)
            xdivisor=gcd(modxy, y)
            modxy//=xdivisor
            y//=xdivisor
    #the above 3 lines reduce the fraction, as do the similar 3 lines in the other bit of code.
            with open ('topheavy.txt','a') as g:
                if modxy!=0 and xy!=0: 
                    b= ('{}/{}={} and {}/{}\n'.format(orx,ory,xy, modxy, y  ))
                    if neg==True:
                        b=(' {}/{}=-{} and {}/{}\n'.format(orx,ory,xy, modxy, y  ))
                    g.write (b)
                elif modxy==0 and xy!=0:     
                    b= ('{}/{}={} \n'.format(orx,ory,xy))
                    if neg==True:
                        b=(' {}/{}=-{} \n'.format(orx,ory,xy))
                    g.write (b)
                elif xy==0:         
                    b=('{}/{}={}/{} \n'.format(orx,ory,modxy, y))
                    if neg==True:
                        b=('{}/{}=-{}/{} \n'.format(orx,ory,modxy, y))
                    g.write (b)
    #this if clause stops the program from saying '5 and 0/5' or a similar thing.
        global index
        index=index+2
mixedfraction()

当我运行它时,我明白了:

66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 2166/556=33/278 
-56/78=-28/39 
43/76=43/76 
6/5=1 and 1/5
98/76=1 and 11/38
4/2=2 
66/54=1 and 2/9
98/21=4 and 2/3
x is not a number.
98/3=32 and 2/3
you cant divide by 0!
0/5=32 and 2/3

你不能除以0&#39;消息是在错误的地方,所以&#39; x不是数字&#39;信息。我不知道如何让他们去正确的地方。然后它在末尾添加了一些奇怪的随机行,这不应该存在。我看了一遍,无法找到解决方案。谢谢你的帮助。

我想要的是:

66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
66/556=answer
-56/78=answer
43/76=answer
you cant divide by 0!
6/5=answer
x is not a number!
98/76=answer
4/2= answer
66/54=answer

1 个答案:

答案 0 :(得分:0)

我的脚本从文件中获取以下数据:

66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 21

并将计算数据保存到同一个文件中:

66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 21

66 / 556 = 33/278
-56 / 78 = -28/39
43 / 76 = 43/76
0 / 5 = 0
6 / 5 = 6/5
a / 4 = Not a number!
98 / 76 = 49/38
4 / 2 = 2
66 / 54 = 11/9
98 / 21 = 14/3

这是Python脚本:

from fractions import Fraction
file = 'topheavy.txt'
outputStr = ''
flag = True

with open(file, 'r') as f:
        for line in f:
            for word in line.split():
                if (flag):
                    dividend = word
                    flag = False
                else:
                    divisor = word
                    try:
                        fraction = Fraction(int(dividend), int(divisor))
                    except ZeroDivisionError:
                        fraction = "You can't divide by 0!"
                    except:
                        fraction = "Not a number!"
                    string = dividend + " / " + divisor + " = " + str(fraction) + "\n"
                    outputStr += string
                    flag = True

f = open(file, 'a')
f.write("\n\n" + outputStr)
f.close()