Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last character of each row in a text file

I have a text file that I need to read and perform an FFT onto.

Basically, the file reads something like this:

1458 1499 1232 1232 1888 ... 2022-09-11 09:32:51.076
1459 1323 1999 1323 1823 ... 2022-09-11 09:32:51.199

and so on. Each row has 200 columns, and I want to basically read each row, up to each column while ignoring the last column that has the time.

So far I've tried this:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

But I don't know how to remove the last characters.

Thank you

like image 780
swapnil Avatar asked Nov 23 '25 17:11

swapnil


2 Answers

Just a little modification on the last line.

[:-2] means all columns except the last two. I guess it's -2 instead of -1 because if you want to omit the datetime you have to omit the date part and the time part (which have been splitted because of the space character), e.g "2022-09-11 09:32:51.076"

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()[:-2])
like image 142
0x0fba Avatar answered Nov 26 '25 05:11

0x0fba


You can use this:

array = []
with open('file.txt','r') as tf:
  for lines in tf.readlines():
    array.append(' '.join(lines.split()[:-2]))

print(array)

If you want to append the list of integers from each of the lines:

array = []
with open('file.txt','r') as tf:
  for lines in tf.readlines():
    array.append([int(x) for x in lines.split()[:-2]])

print(array)
like image 41
Prakash Dahal Avatar answered Nov 26 '25 05:11

Prakash Dahal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!