【问题标题】:Records and field syntax error记录和字段语法错误
【发布时间】:2016-04-28 08:13:36
【问题描述】:

我是编程新手。我现在正在学校学习 python,我遇到了一个错误,我弄明白了。我不断收到语法错误,我不确定是老师的错字还是我自己的错字。

def main():
    num_emps=int(input("How many employee records? "))
    empfile=open("employee.txt","w")
    for count in range(1,num_emps+1):
        print("Enter data for employee#",count,sep='')
        name=input("Name: ")
        id_num=input("ID Number: ")
        dept=input("Department: ")
        empfile=write.(name+"\n")
        empfile=write.(id_num+"\n")
        empfile=write.(dept+"\n")
        print()
    empfile.close
    print("Employee records written to disk")

main()

我不断收到错误

empfile=write.(name+"\n")

或者应该是这样的

empfile.write(name+"\n")

感谢您的帮助

【问题讨论】:

  • 试试吧!另外,要关闭您的文件,请致电 empfile.close() 而不是 empfile.close
  • 我试过仍然得到同样的错误。也感谢您的小错字!
  • 把你得到的详细错误放在你的问题中

标签: python file syntax field records


【解决方案1】:

使用empfile.write() 代替empfile=write.()

【讨论】:

    【解决方案2】:

    更正优化的版本:

    def main():
    
        # indentation was missing in your question:
    
        num_emps = int(input("How many employee records? "))
        empfile = open("employee.txt","w")
    
        for count in range(num_emps):  # range from 0 to num_emps-1
            print("Enter data for employee #{}:".format(count))  # use str.format(...)
    
            name = input("Name: ")
            id_num = input("ID Number: ")
            dept = input("Department: ")
    
            empfile.write(name + "\n")
            empfile.write(id_num + "\n")
            empfile.write(dept + "\n")
            # alternative using Python 3's print function: 
            # print(name, file=empfile)  # line-break already included
    
            print()
        empfile.close()  # to call the function, you need brackets () !
        print("Employee records written to disk")
    
    main()
    

    另外,在您的示例中实际上不需要编写main() 函数。您可以将代码直接放入文件中。
    如果你想要一个正确的 main() 函数,使用这个构造来调用它:

    if __name__ == "__main__":
        main()
    else:
        print("You tried to import this module, but it should have been run directly!")
    

    用于判断一个脚本是直接调用还是被另一个脚本导入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2014-03-29
      • 1970-01-01
      相关资源
      最近更新 更多