2
def read_text_file(filename):
    with open(filename, 'r') as file:
        array = [line.split() for line in file]
    return array

array = read_text_file("file.txt")
print(array[0][1])

Gives a list out of range error

import csv

with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    data = list(reader)

print(data[0][1])

Why is it the csv file to 2d array works and the txt file doesn't? Just curious

2
  • Welcome to Stackoverflow, remember to paste the full error that you get, also please include the file (or a few lines of it)
    – Caridorc
    Commented Feb 5, 2023 at 20:38
  • Please edit your question and include the first few lines of both files, as well as the specific error. Thanks :)
    – Zach Young
    Commented Feb 5, 2023 at 20:52

1 Answer 1

0

Without seeing your inputs we really cannot say for sure, still I can try to approximate what's going on.

Given these TXT and CSV files:

file1.txt     file1.csv
=========     =========
foo FOO       foo,FOO  
bar BAR       bar,BAR  
                       
file2.txt     file2.csv
=========     =========
foo           foo      
bar           bar      

If your program were to read file1.txt and file1.csv, array and data would look like:

[['foo', 'FOO'], ['bar', 'BAR']]

array[0]/data[0] is ['foo', 'FOO'], and the second item from that, [1], is FOO. All is well.

If your program were to read file2.txt and file2.csv, array and data would look like:

[['foo'], ['bar']]

array[0]/data[0] is ['foo'], and the second item from that, [1], doesn't exist. Error, [1] is out of range.

Here's a similar program I wrote that gives me those results:

import csv


def main():
    print("reading TXT files:")
    print("==================")

    for fname in ["file1.txt", "file2.txt"]:
        with open(fname) as f_txt:
            array = [line.split() for line in f_txt]

            try_second_of_first(fname, array)

    print()
    print("reading CSV files:")
    print("==================")

    for fname in ["file1.csv", "file2.csv"]:
        with open(fname, newline="") as f_csv:
            data = list(csv.reader(f_csv))

            try_second_of_first(fname, data)


def try_second_of_first(fname, stuff):
    """Try to print the second "column" from the first line/row of stuff."""
    print(f"{fname}: ", end="")

    try:
        print(stuff[0][1])
    except Exception as e:
        print(f"could not read {stuff}[0][1]: {e}")


if __name__ == "__main__":
    main()

reading TXT files:
==================
file1.txt: FOO
file2.txt: could not read [['foo'], ['bar']][0][1]: list index out of range

reading CSV files:
==================
file1.csv: FOO
file2.csv: could not read [['foo'], ['bar']][0][1]: list index out of range

So, there's nothing different in principle between processing your TXT and CSV files, you just appear to be using differently "shaped" data between the two kinds that's giving different results.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.