Python打开文本文件的方法,选择每个第n个值,然后保存到文本文件.
我有一个包含 57,600,000 百万行值的文本文件.这些值位于文本文件的单列中.它们代表一个重复 2400 次的 150(列)x 160(行)矩阵.我希望完成 2 个不同的操作,每个操作有 3 个目标.
I have a text file that contains 57,600,000 million lines of values. These values are in a single column in the text file. They represent a 150(column) x 160(row) matrix repeated 2400 times. I wish to complete 2 different operations, each with 3 objectives.
操作 1(列)
- 打开文本文件
- 选择每第 n 个数据点
- 将所选值保存到另一个文本或 .csv 文件
操作 2(行)
- 打开文本文件
- 从每第 n 行开始选择一个值范围 (150)
- 将所选值保存到另一个文本或 .csv 文件
这样做的目的是先打印一个矩阵列,然后再打印一行.我是 python 新手用户,正在使用 spyder 运行其他脚本.如果您愿意为我编写脚本,请描述我需要替换的内容以获得所需的结果.我已经浏览了其他类似的帖子,但找不到一个足够相似的帖子,我可以根据自己的需要进行编辑,以我有限的知识.
The point of this is to print a matrix column and then a row. I am a novice python user and am using spyder to run other scripts. If you would be kind enough to write a script for me, please be descriptive on what I would need to replace to get the desired results. I have looked through other similar postings but cannot find a thread that is similar enough that I could edit to my needs, with my limited knowledge.
非常感谢您的关注以及您能提供的任何帮助.
Thank you very much for looking and any assistance you can give.
Python 中的文件是迭代器,这意味着它们可以循环使用,或者对其应用迭代操作.
Files in Python are iterators, meaning they can be looped over, or have iteration operations applied to them.
例如,要获取每 5 行,将是:
To get every 5th line, for example, would be:
import itertools
with open(filename, 'r') as f:
fifthlines = itertools.islice(f, 0, None, 5)
for line in fifthlines:
# do something with line
您也可以使用 islice()
来跳过行;这里我们跳过 10 行,然后读取 10 行:
You can use islice()
to skip lines too; here we skip 10 lines, then read 10:
for line in itertools.islice(f, 10, 20):
# do something with this 10th line
你可以吞下一个系列;因为跳过,然后读取 0 行会引发 StopIteration
信号,我们通过使用 next()
并传入要返回的默认值来吞下它:
You can swallow a series; because skipping, then reading 0 lines raises a StopIteration
signal, we swallow that by using next()
and passing in a default value to be returned instead:
next(itertools.islice(f, 42, 42), None) # skip 42 lines, don't read more
使用 itertools
库,以及快速浏览 Python 教程,您可以很容易地找出脚本的其余部分.
With the itertools
library, and a quick scan through the Python tutorial you can figure out the rest of the script easily enough.