Loading [MathJax]/jax/input/TeX/config.js
社区首页 >问答首页 >如何在使用numpy.fromfile读取文件时跳过行?

如何在使用numpy.fromfile读取文件时跳过行?
EN

Stack Overflow用户
提问于 2022-02-11 08:25:13
回答 2查看 552关注 0票数 0

我正在读取一个.pksc文件,其中包含大量天文物体的坐标和速度。我在做阅读

代码语言:javascript
代码运行次数:0
复制
import numpy as np
f=open('halos_10x10.pksc') 
data = np.fromfile(f,count=N*10,dtype=np.float32)

该文件可以找到这里。它非常大,我想跳过第一个m对象(如果文件中有行,则跳过与这些对象对应的第一个m行)。我怎么能做到这一点,我看不出有什么可以跳过的?另外,也可以跳过文件中的最后一个k对象。Tnx!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-02-11 10:36:29

首先要注意的是,您的PKSC文件是二进制文件,是一个连续的字节字符串,在数据中没有明显的中断。

另一方面,文本文件的行由某些断行字符明确地分隔,所以一次读取,忽略前面的M行,然后读取您关心的其余行数:REMAINING_LINES = ALL_LINES - M_LINES - K_LINES非常容易。

np.fromfile()一次读取二进制文件

要做到这一点,它需要dtype=参数告诉读者一个项目有多大。对于PKSC文件,我们将项表示为32位整数np.int32

我搜索了又搜索,但找不到文件的规范。幸运的是,您提供的链接有一个用于读取文件的样例Python脚本;我还找到了一个文档完整的Python,用于处理这类文件(websk.py,下面链接)。

我了解到PKSC文件具有以下属性:

  • 前3项是头项:
    • 第一个标题项是在标题项之后的相关数据记录的计数。

  • 每个相关数据记录包含10项。

np.fromfile()还将count=参数作为要读取多少项的指示。

下面是如何读取3个标题项,获取后面的Halo记录的总数,并读取前两个记录(每个记录10项):

代码语言:javascript
代码运行次数:0
复制
Nitems_per_record = 10

f = open('halos_10x10.pksc')

headers = np.fromfile(f, dtype=np.int32, count=3)
print(f'Headers: {headers}')
print(f'This file contains {headers[0]} records with Halo data')

record1 = np.fromfile(f, dtype=np.int32, count=Nitems_per_record)
print(f'First record:\n{record1}')

record2 = np.fromfile(f, dtype=np.int32, count=Nitems_per_record)
print(f'Second record:\n{record2}')
代码语言:javascript
代码运行次数:0
复制
Headers: [2079516 2079516 2079516]
This file contains 2079516 records with Halo data
First record:
[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585  1086444250  1170064687 -1011110709 -1006510502]
Second record:
[ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]

根据websky.py,第二和第三标题项目也有相关的价值,也许你也关心这些?我从该代码中合成了以下内容:

代码语言:javascript
代码运行次数:0
复制
RTHMAXin    = headers[1]
redshiftbox = headers[2]

一次读取多个记录需要重新格式化数据。阅读3项记录:

代码语言:javascript
代码运行次数:0
复制
f = open('halos_10x10.pksc')

np.fromfile(f, dtype=np.int32, count=3)  # reading, but ignoring header items

three_records = np.fromfile(f, dtype=np.int32, count=3*Nitems_per_record)
print(f'Initial:\n{three_records}')

reshaped_records = np.reshape(three_records, (3, Nitems_per_record))
print(f'Re-shaped:\n{reshaped}')
代码语言:javascript
代码运行次数:0
复制
Initial:
[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585
  1086444250  1170064687 -1011110709 -1006510502  1170083367 -1013908122
 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354
 -1013985376 -1006510502  1169622353 -1009409432 -1006678295 -1045415727
 -1017794908 -1051267742  1084874393  1169623221 -1009509109 -1006675510]
Re-shaped:
[[ 1170060708 -1011158654 -1006515961 -1022926100  1121164875  1110446585  1086444250  1170064687 -1011110709 -1006510502]
 [ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]
 [ 1169622353 -1009409432 -1006678295 -1045415727 -1017794908 -1051267742  1084874393  1169623221 -1009509109 -1006675510]]

那么,跳下去怎么样?

只需修剪重塑的数据

最简单的方法就是读取所有数据,然后从前面和后面剪裁你不想要的东西:

代码语言:javascript
代码运行次数:0
复制
m = 1
k = 1 * -1
trimmed_records = reshaped_records[m:k]
print(f'Trimmed:\n{trimmed_records}')
代码语言:javascript
代码运行次数:0
复制
Trimmed:
[[ 1170083367 -1013908122 -1006498824 -1014626384 -1020456945 -1033004197  1084104229  1170090354 -1013985376 -1006510502]]

我不知道为什么要跳过,但这是最容易理解和实现的。

如果你的记忆是记忆,那就继续读。

丢弃M记录,读取较少的K+M记录

在我看来,下一个选择是:

  1. 从第一个头获取记录计数(A记录)
  2. 读取和忽略M记录
  3. 考虑到您已经读取了M记录,并且希望在record KR = A - M - K上停下来,请计算出需要读取多少剩余的记录

忽略M记录只会节省一点内存;数据仍然会被读取和解释。最后不读取记录K肯定会节省内存:

代码语言:javascript
代码运行次数:0
复制
f = open('halos_10x10.pksc')
headers = np.fromfile(f, dtype=np.int32, count=3)

Arecords = headers[0]
Mrecords = 1_000_000
Krecords = 1_000_000

Nitems = Mrecords * Nitems_per_record
np.fromfile(f, dtype=np.int32, count=Nitems)

Rrecords = Arecords - Mrecords - Krecords  # Remaining records to read
Nitems = Rrecords * Nitems_per_record
data = np.fromfile(f, dtype=np.int32, count=Nitems)
data = np.reshape(data, (Rrecords, Nitems_per_record))

print(f'From {Arecords} to {Rrecords} records:\n{data.shape}')
代码语言:javascript
代码运行次数:0
复制
From 2079516 to 79516 records:
(79516, 10)
票数 1
EN

Stack Overflow用户

发布于 2022-02-11 15:36:34

如果您只需要将大文件块成较小的文件,那么您就可以独立地对它们进行操作:

代码语言:javascript
代码运行次数:0
复制
import numpy as np

Nrecords_per_chunk = 100_000
Nitems_per_record = 10

f_in = open('halos_10x10.pksc', 'rb')
headers = np.fromfile(f_in, dtype=np.int32, count=3)

Nitems = Nrecords_per_chunk * Nitems_per_record

fnumber = 1
while True:
    items = np.fromfile(f_in, dtype=np.int32, count=Nitems)

    # Because at the end of the file, we're very likely to get less back than we asked for
    Nrecords_read = int(items.shape[0] / Nitems_per_record)

    # At End Of File: Weird luck, chunk_size was a perfect multiple of number of records
    if Nrecords_read == 0:
        break

    records = np.reshape(items, (Nrecords_read, Nitems_per_record))

    with open(f'halos_{fnumber}.pksc', 'wb') as f_out:
        # Keep same format by having 3 "header" items, each item's value is the record count
        new_headers = np.array([Nrecords_read]*3, dtype=np.int32)
        new_headers.tofile(f_out)
        records.tofile(f_out)

    # At End Of File
    if Nrecords_read < Nrecords_per_chunk:
        break

    fnumber += 1

f_in.close()


# Test that first 100_000 records from the main file match the records from the first chunked file

f_in = open('halos_10x10.pksc')
np.fromfile(f_in, dtype=np.int32, count=3)
Nitems = Nrecords_per_chunk * Nitems_per_record
items = np.fromfile(f_in, dtype=np.int32, count=Nitems)
records_orig = np.reshape(items, (Nrecords_per_chunk, Nitems_per_record))
f_in.close()

f_in = open('halos_1.pksc')
np.fromfile(f_in, dtype=np.int32, count=3)
Nitems = Nrecords_per_chunk * Nitems_per_record
items = np.fromfile(f_in, dtype=np.int32, count=Nitems)
records_chunked = np.reshape(items, (Nrecords_per_chunk, Nitems_per_record))
f_in.close()

assert np.array_equal(records_orig, records_chunked)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71083386

复制
相关文章
matlab 行 读取文件 跳过_Matlab读取TXT文件并跳过中间几行的问题!!
#!MLF!#”*/group1.rec”011300000sil-3797.347412SENT-START1130000011600000dh-156.719879the1160000011900000ax-208.4651641190000011900000sp-1.2039731190000012500000ih-482.5331…
全栈程序员站长
2022/10/04
1.9K0
如何在 Python 里优雅地读取文件特定行
如果文件非常大,不能读取到内存中,那么你可能会通过for 循环数行数,数到特定行:
青南
2019/09/16
2.3K0
shell 读取文件行
有道笔记-shell 读取文件行 最近通过Spark Streaming消费Kafka数据,消费的数据落到hdfs,一分钟一个小文件,昨天架构那边的同事告诉我要清理历史文件,但是目录太多,手动删比较慢,于是想到可以把文件目录都拿到,写入文本 path_to_clean.txt,通过shell循环读路径,并执行删除。
大数据工程师-公子
2019/03/14
1.6K0
go:文件按行读取
这里有很大的坑坑。记录一下。 参考代码: fi, err := os.Open(originPath) if err != nil { fmt.Printf("Error: %s\n", err) return } defer fi.Close() br := bufio.NewReader(fi) for { line, err := br.ReadString('\n') if err != nil { // fmt.Println(err)
超级大猪
2019/12/12
1.5K0
C++ 使用 ifstream 按行读取文件内容
其中每行的数字,比如 5 3 是一对坐标,如何使用 C++ 按行读取获取这些坐标?
ClearSeve
2022/02/11
6.2K0
php 按行读取文件信息
首先采用fopen()函数打开文件,得到返回值的就是资源类型。接着采用 while 循环一行行地读取文件,然后输出每行的文字。feof()判断是否到最后一行,fgets()读取一行文本。
Cell
2022/02/25
3.7K0
php 按行读取文件信息
python读取文件末尾N行
# -*- coding: cp936 -*- import os,sys,re def lastline(): global pos while True: pos = pos - 1 try: f.seek(pos, 2) #从文件末尾开始读 if f.read(1) == '\n': break except: #到达文件第一行,直接读取
py3study
2020/01/13
3.3K0
java之文件读取(按单字节读取和按行读取读取)
如果要进行按行读取的话,必须采用BufferedReader BufferedReader中的readline();
IT工作者
2022/03/30
3.1K0
sourceTree安装时跳过登录
3.使用运行或资源管理器输入%LocalAppData%\Atlassian\SourceTree\进入当前用户的SourceTree目录
流柯
2021/09/26
1.8K0
sourceTree安装时跳过登录
JavaNIO实现按行读取文件操作
在Java编程中,文件操作常常是必不可少的步骤。在对文件进行操作时,按行读取文件是一个常见需求。Java提供了多种方法实现按行读取文件,其中一种方法是使用JavaNIO。
用户10354340
2023/08/07
3830
读取除#开头的行的文件
f = open('读取测试文件.txt', 'r', encoding='utf-8') n = open('读取测试文件存储文件.txt', 'w', encoding='utf-8') text = f.readlines() print(text) # 遍历所有行 for i in text: # 便利一行 for flag in range(len(i)): # 如果从第一个位置开始是空格则跳过这个字符往后继续遍历,直到这行结束 if i[flag]
汪凡
2018/05/29
1.7K0
如何在 Python 中读取 .data 文件?
在本文中,我们将学习什么是 .data 文件以及如何在 python 中读取 .data 文件。
很酷的站长
2023/02/22
5.9K0
如何在 Python 中读取 .data 文件?
如何在Java中逐行读取文件
本文翻译自How to read a file line by line in Java
ccf19881030
2020/11/24
10.5K0
读取文件时,程序经历了什么?
当我们使用C语言中的printf、C++中的"<<",Python中的print,Java中的System.out.println等时,这是I/O;当我们使用各种语言读写文件时,这也是I/O;当我们通过TCP/IP进行网络通信时,这同样是I/O;当我们使用鼠标龙飞凤舞时,当我们扛起键盘在评论区里指点江山亦或是埋头苦干努力制造bug时、当我们能看到屏幕上的漂亮的图形界面时等等,这一切都是I/O。
范蠡
2020/12/15
1.1K0
读取文件时,程序经历了什么?
2、while+read按行读取文件
一、三种方法 1.exec读取文件 exec <file sum=0 while read line do cmd done 2. cat读取文件 cat file|while read line do cmd done 推荐用途: 通过awk等三剑客获取文件中的数据后,可以使用这种方法用管道抛给while按行读取 3. while循环最后加重定向 while read line do cmd done<file 推荐用途: 直接按行读取文件中的内容时,推荐用此方法 二、案例 读取web日志文件
jackxiao
2021/11/16
1.7K0
Maven打包时跳过测试类
Maven打包时跳过测试类 在springboot项目中,默认会有Test测试类,如果执行maven打包命令,会运行测试类,而这是不必要 最简单的方法,在pom文件设置一个maven自带变量即可 <properties> <skipTests>true</skipTests> </properties>
4xx.me
2022/06/09
4340
Maven打包时跳过测试类
python读取文件如何去除空格_python读取txt文件时怎么去掉空格
Python读取TXT文件可以通过replace()函数来去除TXT文件中的空格,基本结构:replace(to_replace, value) 前面是需要替换的值,后面是替换后的值。
全栈程序员站长
2022/08/24
6.6K0
如何在python中惰性地读取文件?
惰性地读取,就是在读文件的时候,不是直接将整个文件读到内存之中,而是一行一行的读取。这对于读取如网页日志这样的贼大的文件来说,可以减少打开文件的响应时间以及所占用的内存。
灯珑LoGin
2022/10/31
1.8K0
点击加载更多

相似问题

使用reg ex读取文件时跳过行

29

如何在使用紧凑框架3.5读取文件时跳过行

11

如何在java中读取文件时跳过行

1274

使用for循环读取文件时跳过一行

21

使用Pandas读取excel文件时跳过特定行

246
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文