在python中格式化新文件的问题

时间:2016-03-28 00:22:34

标签: python file-processing script-debugging

所以我对python(以及一般的编码)都很陌生,我可以使用一些认真的帮助在我的代码中找到问题。    基本上,我打开的文件包含任意数量的学生姓名,然后是4个考试成绩。所以像这样:

John
78.0
80.0
69.0
98.0
Bob
40.0
78.0
77.0
89.0
etc

我的程序假设然后读取所述文件并输出到shell:

  John: 78.0 80.0 69.0 98.0 Average: 81.25
  Bob: 40.0 78.0 77.0 89.0 Average: 71.0

最后它应该将名称和平均值保存到新文件中,如

  John,81.25
  Bob, 71.0

但是我的程序将其打印到屏幕上:

Mary
 :76.0 89.0 82.0 100.0 Average: 86.75
Joey
 :91.0 81.0 83.0 95.0 Average: 87.5
Sally
 :92.0 93.0 90.0 97.0 Average: 93.0

正在保存这样的文件:

  Mary
  86.75Joey
  87.5Sally
  93.0

任何人都可以帮助解决这些问题吗?它的学校作业只是帮助识别我的错误编码就足够了。

这是我的一堆代码:

创建包含学生分数的文件

scoresa = open('project3-scoresa.txt','w')
scoresa.write("Mary\n76\n89\n82\n100\nJoey\n91\n81\n83\n95\nSally\n92\n93\n90\n97")
scoresa.close()



def main():
    averages = open("averages.csv","w")
    file = input("Please enter the scores filename:")
    try:
        scores = open(file,'r')
        print("File",file,"has been opened")
    except IOError:
        print("File",file,"could not be opened.")
    scores = open(file,'r')
    i = 0
    for line in scores:
        if i%5 == 0:
            name = line
            print(name.strip("/n"),":", end="")
            j = 1
            total = 0
        else:
            score = float(line)
            print(score, end=" ")
            total += score
            ave = total/j
            if j == 4:
                print("Average:",ave)
                Avestring = (name + str(ave))
                averages.write(Avestring)
            j += 1
        i += 1
    scores.close()
    averages.close()
    average = open("averages.csv","r")
    for line in average:
        print(line.strip("\n"))
main()

3 个答案:

答案 0 :(得分:1)

你非常接近。试试这个。

def main():
    averages = open("averages.csv","w")
    file = input("Please enter the scores filename:")
    try:
        scores = open(file,'r')
        print("File",file,"has been opened")
    except IOError:
        print("File",file,"could not be opened.")
    scores = open(file,'r')
    i = 0
    for line in scores:
        if i%5 == 0:
            name = line.strip("\n")
            print(name,":", end="")
            j = 1
            total = 0
        else:
            score = float(line)
            print(score, end=" ")
            total += score
            ave = total/j
            if j == 4:
                print("Average:",ave)
                Avestring = (name + "," + str(ave) + "\n")
                averages.write(Avestring)
            j += 1
        i += 1
    scores.close()
    averages.close()
    average = open("averages.csv","r")
    for line in average:
        print(line.strip("\n"))
main()

主要变化是:

name = line.strip("\n") # note the \n not /n
print(name,":", end="")

Avestring = (name + "," + str(ave) + "\n") # note the comma and line break.

答案 1 :(得分:0)

你在这一行有一个错字:

print(name.strip("/n"),":", end="")

即。你应该有\n(表示新行字符的转义序列),而不是/n

这意味着打印时不会从名称中删除换行符,这就是为什么你有这样的输出:

Mary
 :76.0 89.0 82.0 100.0 Average: 86.75

而不是:

Mary:76.0 89.0 82.0 100.0 Average: 86.75

(请注意,您还需要在:之后添加空格以获得目标输出)

请注意,即使您使用过name.strip('\n')(即没有拼写错误),在写入文件时仍会看到第二个问题。在strip()上调用name不会改变name本身的值,因此当您执行此操作时换行符仍在name中:

Avestring = (name + str(ave))
averages.write(Avestring)

要更新name的价值,请执行以下操作:

name = name.split('\n')

获取name的旧值,在其上调用split()并将返回的结果存储回name

但是,在这种情况下,你可以这样做:

name = line.split('\n')

因为您从不需要包含换行符的名称,所以也可以立即将其删除。

答案 2 :(得分:0)

第一个问题可以通过在第20行中用“\ n”替换“/ n”来解决:

StringProperty

这将转向:

 print(name.strip("/n"),":", end="")

我所做的其他改变是第19和30行。我首先为新行字符填充字符串。新的代码行将是。

 print(name.strip("\n"),":", end="")