Sanskar Agarwal
Sanskar Agarwal

Reputation: 1

Unable to print data using CSV in Python

In the display function I am not able to print the table created. It is showing no error. just printing None. Please help me. Also this is similar in all the functions using csv.reader(). This is school work. I need to get it done soon.

def display():
    flag = 0
    data = None
    with open('student.csv', 'a+', newline="") as f:``
        reader = csv.reader(f)
        for i in reader:
            print(i)
            if flag == 0:
                data = prettytable.PrettyTable(i)
                flag = 1
            else:
                data.add_row(i)
    print(data)
def search():
    with open('student.csv', 'a+', newline="") as f:
        ch = "Y"
        while ch == 'Y':

            lst = ["Roll No.", 'Class', 'Section', 'Student Name', 'Marks']
            rno = int(input("Enter Roll No. of Student to be searched:"))
            reader = csv.reader(f)
            for i in reader:
                if i[0] == rno:
                    print("Data Found")
                    for j in range(len(lst)):
                        print(f"{lst[j]}:{i[j]}")
            ch = input("Do you want to search more(Y/N)?:").upper()
def delete():
    ch = 'Y'
    while ch == 'Y':
        with open('student.csv', 'a+', newline="") as f:
            flag = 0
            rno = int(input("Enter Roll No. of Student to be deleted:"))
            with open('student2.csv', 'w+', newline="") as f2:
                write2 = csv.writer(f2)
                reader = csv.reader(f)
                for i in reader:
                    if i[0] != rno:
                        write2.writerow(i)
                    else:
                        print("Data found")
                        flag = 1
        os.remove('student.csv')
        os.rename('student2.csv', 'student.csv')
        if flag == 0:
            print("Data does not exists")
        ch = input("Do you want to delete more(Y/N)?:").upper()

Upvotes: 0

Views: 43

Answers (1)

nspo
nspo

Reputation: 1518

Instead of reading, what you want, you told Python to append to the file (due to a in the open call). You should write:

with open('student.csv', 'r', newline="") as f:

with 'r' for reading. This leads to, e.g.

['1', '2', '3']
['4', '5', '6']
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+

You can also just skip writing the 'r' because it is the default.

For more information: https://docs.python.org/3/library/functions.html#open

Upvotes: 1

Related Questions