Home > Back-end >  How do you read .txt with tab separated items that are on one line to a list?
How do you read .txt with tab separated items that are on one line to a list?

Time:06-14

I have this .txt: '4 1 15 12'

It's just one long line separating its' items with tab. I need to read it into a list containing int items.

I can't seem to make pandas, csv module or open to do the trick.

This kinda works:

f = open('input.txt') 
for line in f:
    memory = line.split()
for item in memory:
    item = int(item)

print(memory)

['4', '1', '15', '12']

But it gives me an error when i compare its' max value to an int:

 max_val = max(memory)
 while max_val > 0:
TypeError: '>' not supported between instances of 'str' and 'int'

CodePudding user response:

its a TypeError you cant check if a type(str) is a type(int) because they are both different types

max_val = max(memory)
print(type(max_val))
>>> <class 'str'>

just change max_val to an int for example

max_val = max(memory)
while int(max_val) > 0:

CodePudding user response:

It appears as though the text in the question was not tab spaced. I have created a tab spaced file and the following works:

import pandas as pd

test_file = "C:\\Users\\lefcoe\\Desktop\\test.txt"

df = pd.read_csv(test_file, delimiter='\t', header=None)

print(df)



#%% convert to a list of ints
my_list = df.loc[0, :].values.tolist()
my_list_int = [int(x) for x in my_list]
my_list_int

#%% get the max
m = max(my_list_int)
print(m)

result:

   1  1  2  3
0  4  1  15 12

15
  • Related