-1

我有一个包含 57,600,000 百万行值的文本文件。这些值位于文本文件的单个列中。它们代表一个重复 2400 次的 150(列)x 160(行)矩阵。我希望完成 2 个不同的操作,每个操作有 3 个目标。

操作 1(列)

  1. 打开文本文件
  2. 选择每第 n 个数据点
  3. 将所选值保存到另一个文本或 .csv 文件

操作 2(行)

  1. 打开文本文件
  2. 从每第 n 行开始选择一系列值 (150)
  3. 将所选值保存到另一个文本或 .csv 文件

这样做的目的是先打印一个矩阵列,然后再打印一行。我是新手 python 用户,正在使用 spyder 运行其他脚本。如果您愿意为我编写脚本,请描述我需要替换的内容以获得所需的结果。我浏览了其他类似的帖子,但找不到足够相似的线程,我可以根据我的需要进行编辑,我的知识有限。

非常感谢您寻找和提供任何帮助。

4

1 回答 1

10

Python 中的文件是迭代器,这意味着它们可以被循环,或者对它们应用迭代操作。

例如,要获取每 5 行,将是:

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:

for line in itertools.islice(f, 10, 20):
    # do something with this 10th line

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

With the itertools library, and a quick scan through the Python tutorial you can figure out the rest of the script easily enough.

于 2012-12-15T15:48:46.217 回答