-1

I currently have a text file containing data like so

0
0
0
1
0
1
5...

I'm struggling to read the file in as a list [0,0,0,1,0,5...] or as a numpy array. These txt files are around 400 lines of data. using the f.readlines() function is currently giving me a list that looks like ['0/n','0/n','0/n','1/n','0/n','5/n'...]. if anyone knows a good way of doing this it would be much appreciated.

Sam Sloan
  • 49
  • 4

4 Answers4

0

get the line content with f.readline() but while inserting the content into your list, exclude the last character as that is a new line character. Assuming you are working with python do something like this

x[i] = f.readline()[:-1] 

where x is the name of your list.

Saifullah
  • 11
  • 2
0

You can either run a replace to remove the escape characters:

np.core.defchararray.replace(arr,'\n', '    ')

where arr is the array from which you want to remove the escape characters. Check also here

Or you can have a quick look here

You may also use:

for line in lines:
    print(line.rstrip())
Svestis
  • 123
  • 1
  • 8
0

If you are getting an array with newline characters, you can replace them as follows:

> a = ['0/n','0/n','0/n','1/n','0/n','5/n'] r = map(lambda x:
> x.replace('/n', ''), a) print(list(r))

This prints

[0,0,0,1,0,5]

But I don't find the approach elegant. Has to be a better way.

Sid
  • 4,510
  • 14
  • 51
  • 100
0

You can cast from string to int with astype

num_list = np.array(list_with_endlines).astype(np.int64))
Kostas
  • 3,822
  • 11
  • 28