简体   繁体   中英

How do I put all my looped output in a variable (for generating an output file)? (CSV related)

I am quite new to working with python, so i hope you can help me out here. I have to write a programm that opens a csv file, reads it and let you select columns you want by entering the number. those have to be put in a new file. the problem is: after doing the input of which columns i want and putting "X" to start the main-part it generates exactly what i want but by using a loop, not printing a variable that contains it. But for the csv-writer i need to have a variable containg it. any ideas? here you have my code, for questions feel free to ask. the csvfile is just like:

john, smith, 37, blue, michigan
tom, miller, 25, orange, new york
jack, o'neill, 40, green, Colorado Springs
...etc

Code is:

import csv

with open("test.csv","r") as t:
    t_read = csv.reader(t, delimiter=",")
    t_list = []
    max_row = 0
    for row in t_read:
        if len(row) != 0:
            if max_row < len(row):
                max_row = len(row)
            t_list = t_list + [row] 
            print([row], sep = "\n")
    twrite = csv.writer(t, delimiter = ",")
    tout = []
    counter = 0
    matrix = []
    for i in range(len(t_list)):
        matrix.append([])
    print(len(t_list), max_row, len(matrix), "Rows / Columns / Matrix Dimension")
eingabe = input("Enter column number you need or X to start generating output: ")
nr = int(eingabe)
while type(nr) == int:
    colNr = nr-1
    if max_row > colNr and colNr >= 0:
        nr = int(nr)
        # print (type(nr))
        for i in range(len(t_list)):            
            row_A=t_list[i]            
            matrix[i].append(row_A[int(colNr)])
            print(row_A[int(colNr)])
        counter = counter +1
        matrix.append([])
    else:
        print("ERROR")

    nr = input("Enter column number you need or X to start generating output: ")

    if nr == "x":
        print("\n"+"Generating Output... "  + "\n")        
        for row in matrix:
    # Loop over columns.           
            for column in row:     
                print(column + " ", end="")
            print(end="\n")

    else:
        nr = int(nr)

print("\n")


t.close()

Well you have everything you need with matrix , apart from an erroneous line that adds an unneeded row:

    counter = counter +1
    matrix.append([])   # <= remove this line
else:
    print("ERROR")

You can then simply do:

if nr == "x":
    print("\n"+"Generating Output... "  + "\n")        
    with open("testout.csv", "w") as out:
        wr = csv.writer(out, delimiter=",")
        wr.writerows(matrix)

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