【问题标题】:Issues formatting a new file in python在 python 中格式化新文件的问题
【发布时间】:2016-07-15 05:35:50
【问题描述】:

所以我对 python(和一般编码)还是很陌生,我可以使用一些认真的帮助来发现我的代码中的问题。 基本上,我打开一个文件,其中包含任意数量的学生姓名和 4 个考试成绩。所以是这样的:

John
78.0
80.0
69.0
98.0
Bob
40.0
78.0
77.0
89.0
etc

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

  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()

【问题讨论】:

    标签: python file-processing script-debugging


    【解决方案1】:

    你在这行有一个错字:

    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')(即没有错字),在写入文件时您仍然会看到第二个问题。在name 上调用strip() 不会改变name 本身的值,因此当你这样做时,换行符仍在name 中:

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

    要更新name 的值,您可以:

    name = name.split('\n')
    

    它采用name 的旧值,对其调用split() 并将返回的结果存储回name。

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

    name = line.split('\n')
    

    由于您永远不需要包含换行符的名称,因此不妨立即将其删除。

    【讨论】:

      【解决方案2】:

      你很亲密。试试这个。

      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.
      

      【讨论】:

      • 谢谢!这是一个很大的帮助。
      • 在接受答案之前您还需要更多建议吗?
      【解决方案3】:

      您的第一个问题可以通过将第 20 行中的“/n”替换为“\n”来解决:

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

      这将变成:

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

      我所做的其他更改位于第 19 和 30 行。我首先删除了换行符的字符串。新的代码行将是。

      name = line.strip("\n")
      Avestring = (name +","+ str(ave)+ "\n")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 2015-12-05
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        相关资源
        最近更新 更多