swa*_*nil 2 python filesystems
我有一个文本文件,需要读取它并对其执行 FFT。
基本上,该文件的内容如下:
1458 1499 1232 1232 1888 ... 2022-09-11 09:32:51.076
1459 1323 1999 1323 1823 ... 2022-09-11 09:32:51.199
Run Code Online (Sandbox Code Playgroud)
等等。每行有 200 列,我想基本上读取每一行,直至每一列,同时忽略有时间的最后一列。
到目前为止我已经尝试过这个:
1458 1499 1232 1232 1888 ... 2022-09-11 09:32:51.076
1459 1323 1999 1323 1823 ... 2022-09-11 09:32:51.199
Run Code Online (Sandbox Code Playgroud)
但我不知道如何删除最后一个字符。
谢谢
你可以使用这个:
array = []
with open('file.txt','r') as tf:
for lines in tf.readlines():
array.append(' '.join(lines.split()[:-2]))
print(array)
Run Code Online (Sandbox Code Playgroud)
如果要附加每行中的整数列表:
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)
Run Code Online (Sandbox Code Playgroud)
只需对最后一行稍加修改即可。
[:-2] 表示除最后两列之外的所有列。我猜它是-2而不是-1,因为如果你想省略日期时间,你必须省略日期部分和时间部分(由于空格字符而被分割),例如“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])
Run Code Online (Sandbox Code Playgroud)