Reputation: 45
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
Upvotes: 2
Views: 263
Reputation: 4875
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)
Upvotes: 5
Reputation: 1620
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])
Upvotes: 5
Reputation: 107
I agree with all previous answers, many ways to solve this. This seems to do the trick for my test-file:
array = []
with open('file.txt') as f:
for line in f:
w = [x for x in line.split()] # read first line
array.append(w[:-1])
Upvotes: 1
Reputation: 833
Many ways to solve this. One way is to read each line as a listand then take all but the last item:
a = [1,2,3]
b = a[:-1]
print b
then use the resulting list b
Upvotes: 1