简体   繁体   中英

Only printing one line of csv file

I'm trying to print every line in a csv file however it will only print the first one. Heres the code that is responsible:

    if option == '1':
    with open("songs.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            output = (row[0], row[1], row[2]) #Only outputs 1 song ?
            print (output)

Here is the full code if needed:

def list():
option = input ('Enter 1 to print a list of all songs or Enter 2 to print songs in a certin genre: ')
if option == '1':
    with open("songs.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            output = (row[0], row[1], row[2]) #Only outputs 1 song ?
            print (output)

            outputtxt_check = False

            while outputtxt_check == False:
                outputtxt = input ("Would you like to output this list to a text file? Enter 1 for yes or 2 for no: ")

                if outputtxt == '1':
                    text_file = open('list.txt', 'w')
                    text_file.write(str(output))
                    text_file.close()
                    outputtxt_check = True
                    print ("Text File Created Successfully!")
                    menu()

                elif outputtxt == '2':
                    (list)
                    outputtxt_check = True
                    menu()

                else:
                    print('Enter 1 or 2')
                    outputtxt_check = False
                    list()

Thank You in advance :)

The part of the code where you list the songs is working for me.

if option == '1':
    with open("songs.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            output = (row[0], row[1], row[2]) #Only outputs 1 song ?
            print (output)

However, the stuff you write after, while it is looping, eg

outputtxt_check = False

                while outputtxt_check == False:
                    outputtxt = input(
                        "Would you like to output this list to a text file? Enter 1 for yes or 2 for no: ")

is happening while in the same for loop. That's why it's printing only one line. You're asking user the question while the for loop is not finished printing all the songs yet. Try putting the while loop outside/after for loop is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM