Hello,

I'm currently working a project for class and I've gotten stuck. I am suppose to write a program that will read a csv file and create a text file with information from this csv file.

So, far I have code that prompts for the file name and gives a "File not found" message, if the file does not exsist and will prompt over and over again until a vaild file name is entered. What I'm stuck on is a function that I've created to get the values of a certain column into a list. The code is below:

def get_values(file, column_index):

    '''(str, int) -> list

    Return a list of values in file at colum_index''' 

    value_list = []

    for line in file:
        line_list = line.split('.')
        value_list.append(line_list[column_index])

    return value_list

while True:
    try:
        file_name = input('Enter in file name: ')
        input_file = open(file_name, 'r')
        break

    except IOError:
         print('File not found.')

I'm trying to make the code general as possible so that any csv file and column index can be used. When I run the program though, I get an error message for the line "value_list.append(line_list[column_index])". Why is that? I thought using a variable like this was valid.

Thanks for any help.

Recommended Answers

All 2 Replies

I'm trying to make the code general as possible so that any csv file and column index can be used.

There is some work if you want to reach this universality. Csv files may vary on their encoding, their quoting strategy, their separator. See the csv module's documentation, especially the part about dialects and the discussion about unicode.

The most obvious possible error in your code is if column_index is larger than the length of a line. You will get an IndexError!

Thank you for the information. I meant to say the same file, but maybe it is updated annually. I figured it out after changng some things. Here is the code:

def get_values(file, index):
    values_list = []
    for line in file:
        line_list = line.split(',')
        values_list.append(line_list[index])
    return values_list





while True:
    try:
        file_name = input('Enter in file name: ')
        input_file = open('riskfactors.csv', 'r')
        break

    except IOError:
         print('File not found.')




heart_list = get_values(input_file, 1)

I'm pretty sure there is a more efficent way, but this works for me. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.