搜索.CSV文件

时间:2014-11-15 14:10:02

标签: python csv external

我一直在尝试在python中创建一个程序,您可以在CSV文件中访问,搜索和输入(追加)数据。我可以追加并打印文件,但是我在搜索外部文件时遇到问题。

这是我的代码到目前为止的样子:

def a():
    # knows to use the file (getting something that's made)
    import csv

    myfile = open("student01.csv", "a")

    student_num = input("Enter the student number: ")
    name = input("Enter student's name: ")
    tutor_group = input("Enter the tutor group: ")
    gender = input("Enter M or F: ")

    new_record =student_num+","+name+","+tutor_group+","+gender

    myfile.write(str(new_record))
    myfile.write("\n")

    myfile.close()

def d():
    # knows to use the file (getting something that's made)
    import csv

    myfile = open("student01.csv", "rb")
    reader = csv.reader(myfile)
    for row in myfile:
        print(row)

    myfile.close()

def menu():
    print("Welcome to Student.csv\nWhat would you like to do?")
    print()
    print("1. Add to the file")
    print("2. Display all the data from the file")
    print("3. Search for particular data")
    enter = input("Enter 1, 2 or 3: ")
    enter = enter.upper()
    if enter == "1":
        a()
    elif enter == "2":
        d()
   else:
        s()

    menu()

我只是不确定我的def s():现在要做什么,以便我能够通过他们的姓名,号码或辅导组搜索文件中的学生。

有没有人有任何想法?

洛茨

3 个答案:

答案 0 :(得分:1)

csv模块中有一个DictReader,非常适合您想做的事情(假设某些字段是唯一的,可能是student_num)

仅供参考我在您的代码中看到了一些问题

    如果没有必要,
  1. 不要在功能中导入模块,不要重复自己(DRY),只需在任何函数外部放置一个import语句,如果导入了某些内容,请使用它;)
  2. 使用函数的参数,而不是在文件名
  3. 的正文中使用常量字符串
  4. 这个:student_num+","+name+","+tutor_group+","+gender应该删除,使用', '.join(your_iterable)代替
  5. 当你想打开一个文件并在关闭之前对它进行处理时,使用一个上下文管理器:`with open(' myfile.txt')作为flux:',它定义了一个阻止打开文件的位置,即使出现问题并引发异常,文件也会自动关闭

答案 1 :(得分:1)

import csv

def create_record(number_of_students):

    while number_of_students:
        student_num = raw_input("Enter the student number: ")
        name = raw_input("Enter student's name: ")
        tutor_group = raw_input("Enter the tutor group: ")
        gender = raw_input("Enter M or F: ")

        if student_num and name and tutor_group and gender:
            record_list = [student_num, name, tutor_group, gender]

            with open("student_record.csv", "ab") as wf:
                 writer = csv.writer(wf)
                 writer.writerow(record_list)
        number_of_students -= 1

def display_record(option):

    with open("student_record.csv", "r") as rf:
        reader = csv.reader(rf)
        if option == 2:
            for row in reader:
                print "  ".join(row)
        elif option == 3:
            search_feild = raw_input("Search by student name, number, tutor_group, gender :")
            for row in reader:
                if search_feild in row:
                    print "  ".join(row)


def main():
    print("1. Add to the file")
    print("2. Display all the data from the file")
    print("3. Search for particular data")
    print("0. To Exit")

    choice = True
    while choice:
        your_choice = input("Enter your choice:")
        if your_choice == 1:
            number_of_students = input("Enter number of records you want to enter:")    
            create_record(number_of_students)
        if your_choice == 2:
            display_record(2)
        if your_choice == 3:
            display_record(3)
        if your_choice == 0:
            choice = False

if __name__ == "__main__":
    main()    

Output:
1. Add to the file
2. Display all the data from the file
3. Search for particular data
0. To Exit
Enter your choice:1
Enter number of records you want to enter:3
Enter the student number: 1
Enter student's name: Jhon
Enter the tutor group: Python
Enter M or F: M
Enter the student number: 2
Enter student's name: Lina
Enter the tutor group: Django
Enter M or F: F
Enter the student number: 3
Enter student's name: Max
Enter the tutor group: Python
Enter M or F: M
Enter your choice:2
1  Jhon  Python  M
2  Lina  Django  F
3  Max  Python  M
Enter your choice:3
Search by student name, number, tutor_group, gender :Python
1  Jhon  Python  M
3  Max  Python  M
Enter your choice:3
Search by student name, number, tutor_group, gender :F
2  Lina  Django  F
Enter your choice:0

您甚至应该使用 csv writer 方法在csv文件中编写数据。

搜索很容易,因为在阅读csv时,它会提供列表,我们可以使用 关键字搜索任何元素。

答案 2 :(得分:0)

搜索一组记录并不是一个小问题。我希望这不会让你变得非常复杂,但你需要做一些事情:

  1. 您要搜索的每个字段的索引(复制信息以便快速查找的数据结构)
  2. 一种聪明的方式来猜测用户是否输入了姓名,导师组或号码(或只是询问他们想要搜索的内容)
  3. 你可以在这里制作自己的东西:可以先将用户的输入编译成正则表达式,然后通过在条目和用户查询之间进行二进制比较来搜索CSV文件的子集(如名称列)。

    你也可以制作一个索引:只需选择一种数据类型(或者当然是自己制作),并确保在合理的时间内检查自己的记录数量是否超级有效(低至a)时间复杂度尽可能)。

    然后,很多人长期以来一直在研究这个问题,并且有很多代码可以帮助你。查看Information Retrieval并了解您正在查看的问题类型。

    您可以使用类似Xapian的内容进行搜索,但有很多替代方法。

    以下是一些可能对您有帮助的问题:没有选择{{}}}的问题,使用answer函数的问题,以及正确看待any的问题

相关问题