Python打开文本文件的方法,选择每个第n个值,然后保存到文本文件. [英] Python way to open a text file, select every nth value, and save to a text file.

查看:53
本文介绍了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(列)

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

操作 2(行)

  1. 打开文本文件
  2. 从每第 n 行开始选择一个值范围 (150)
  3. 将所选值保存到另一个文本或 .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.

这篇关于Python打开文本文件的方法,选择每个第n个值,然后保存到文本文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆