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.