简体   繁体   中英

Python: convert csv file to list of tuples

My program is supposed to take data from a csv file and turn each row into a tuple organized by column. However when I run it, it returns the tuples as every character as a tuple element, rather than aa tuple of strings. For example if a row is organized by these columns: 'Order Date', 'Order Date', 'Group', 'Description', it should be return them as a tuple with each of those headers as an element of the tuple (4 elements). How can I fix it to return the tuples properly?

Here is the code:

import csv

def list_to_tuple(input_file):
csvfile = open(input_file)  #open the input file
input_content = csvfile.readlines()  #get the content of the input file and store as a double array
csvfile.close() # dont need the file anymore i can close it


final_list = []

    for lines in range(len(input_content)):
        input_content[lines] = input_content[lines].split(',')

    for lines in range(len(input_content)):
        for words in range(len(input_content[lines])):
            input_content[lines][words] = input_content[lines][words].strip()
            input_content[lines][words] = input_content[lines][words].lower()


    for i in range(len(input_content)):
        Order_Date = input_content[i][0]
        Order_ID = input_content[i][1]
        Group = input_content[i][2]
        Item_Category = input_content[i][3]
        Description = input_content[i][4]
        Seller = input_content[i][-2]
        Item_Total = input_content[i][-1]
        item = ('{},{},{},{},{},{},{}'.format(Order_Date, Order_ID, Group, Item_Category, Description, Seller, Item_Total))
        final_list.append(tuple(item))
    return final_list

input_file = 'orders.csv'
final_output = list_to_tuple(input_file)
print(final_output)

and here is a snippet of the incorrect output: 在此处输入图片说明

and here is what the csv file looks like: 在此处输入图片说明

Reading a CSV file using the CSV module would likely make this much simpler.

For example:

import csv
with open('myfile', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    output = list(reader)

That would get you the data as a list of lists. If you needed them to be tuples you could convert from there.

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