【问题标题】:How to make data entered by user to appear below headers如何使用户输入的数据显示在标题下方
【发布时间】:2017-08-25 16:06:06
【问题描述】:

这是我输入学生详细信息的代码。用户输入详细信息并输入“是”后,详细信息将导出到 StudentDetails.csv (Microsoft Excel),它应该位于标题下方,但最终会转到其他位置。

def EnterStudent():
    uchoice_loop = False
    ask_loop = False
    while uchoice_loop == False:
            surname = raw_input("What is the surname?")
            forename = raw_input("What is the forname?")
            date = raw_input("What is the date of birth? {Put it in the format D/M/Y}")
            home_address = raw_input("What is the home address?")
            home_phone = raw_input("What is the home phone?")
            gender = raw_input("What is their gender?")
            tutor_group = raw_input("What is their tutor group?")
            email = (forename.lower() + surname.lower() + ("@school.com"))
            print(surname+" "+forename+" "+date+" "+home_address+" "+home_phone+" "+gender+" "+tutor_group+" "+email)
            ask = raw_input("Are these details correct?"+"\n"+"Press b to go back, or yes to add entered data on your student.").lower()
            if ask == "yes":
                    f = open("StudentDetails.csv","rt")
                    lines = f.readlines()
                    f.close()
                    lines.append(surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email+"\n")
                    f = open("StudentDetails.csv", "w")
                    f.writelines(lines)
                    f.close()
                    uchoice_loop = True
                    printMenu()
            elif ask == "b":
                    uchoice_loop = False
            else:
                 print("Plesase enter 'b' to go back or 'yes' to continue")

这是我的 csv 文件。 enter image description here

【问题讨论】:

  • 欢迎来到 Stack Overflow!请编辑您的帖子以提供更多信息。相反,数据会去哪里?您收到哪些错误消息?这将帮助我们帮助您。

标签: python python-2.7 csv


【解决方案1】:

您可以做一些事情来完成这项工作。您无需打开 StudentDetails.csv 并阅读所有行。相反,您可以创建一个 lines 字符串变量并将其附加到 StudentDetails.csv 中,如下例所示

#f = open("StudentDetails.csv","rt")
#lines = f.readlines()
#f.close()
lines = surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email

# the "a" appends the lines variable to the csv file instead of writing over it like the "w" does
f = open("StudentDetails.csv", "a") 
f.writelines(lines)
f.close()
uchoice_loop = True

【讨论】:

    【解决方案2】:

    Eric 是对的,您最好以附加模式打开文件(请参阅 https://docs.python.org/3.6/library/functions.html#open),而不是一遍又一遍地繁琐地读取和重写文件。

    我想补充一点,您可能也会喜欢使用标准库的csv 模块(请参阅https://docs.python.org/3.6/library/csv.html),特别是如果您以后想在 Excel 中使用您的输出文件。

    然后,我还建议您不要将变量用于 while 循环条件,而是了解 continue 和 break 语句。如果您想跳出示例中的外循环,请研究try、except 和raise。

    最后,除非你真的必须使用 Python 2.x,否则我建议你开始使用 Python 3。下面的代码是用 Python 3 编写的,在 Python 2 中不起作用。

    #!/usr/bin/env python
    # -*- codig: utf-8 -*-
    
    import csv
    
    
    def enterStudent():
        b_or_yes = 'Press b to go back, or yes to save the entered data: '
        while True:
            surname = input('What is the surname? ')
            forename = input('What is the first name? ')
            date = input(
                'What is the date of birth? {Put it in the format D/M/Y} ')
            home_address = input('What is the home address? ')
            home_phone = input('What is the home phone? ')
            gender = input('What is the gender? ')
            tutor_group = input('What is the tutor group? ')
            email = forename.lower() + surname.lower() + '@school.com'
            studentdata = (
                surname,
                forename,
                date,
                home_address,
                home_phone,
                gender,
                tutor_group,
                email)
            print(studentdata)
            while True:
                reply = input('Are these details correct?\n' + b_or_yes).lower()
                if reply == 'yes':
                    with open('studentdetails.csv', 'a', newline='') as csvfile:
                        studentwriter = csv.writer(csvfile, dialect='excel')
                        studentwriter.writerow(studentdata)
                    break
                elif reply == 'b':
                    break
    
    
    if __name__ == '__main__':
        enterStudent()
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2013-07-27
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多