如何部分读取文本文件并将其写入另一个文本文件

我是新来的,有一个问题。我没有那么多关于编程的知识,因为我只是一个初学者,所以我想得到尽可能简单的答案。当然,我会尽力理解他们!英语也不是我的第一语言。为我糟糕的英语道歉。


我想做的任务

我有a.txt包含由以下描述的 100 行数据:


import numpy as np

b = np.arange(0.005, 0.05, 0.0001)

c = np.arange(1.5, 2.51, 0.01)


with open('a.txt','w') as f:

    for a in range(1,101):

        f.write('{:<3d} {:<3f} {:<3f}\n'.format(a,b[a-1],c[a-1]))

a.txt 上的数据如下所示:


1   0.005000 1.500000

2   0.005100 1.510000

3   0.005200 1.520000

4   0.005300 1.530000

5   0.005400 1.540000

6   0.005500 1.550000

7   0.005600 1.560000

8   0.005700 1.570000

....

97  0.014600 2.460000

98  0.014700 2.470000

99  0.014800 2.480000

100 0.014900 2.490000

现在,我只想选择第 1 行到第 10 行的数据并将其写入另一个文本文件 b.txt。我怎样才能做到这一点?


为简单起见,我现在正在处理一个非常小的文件,但我想在将来对一个非常大(如几 GB)的文本文件执行此任务,因此我想知道执行此任务的方式也可以用来处理大文件。


如果有任何我没有显示但有必要的信息,请告诉我。我会尽快添加它。


我很感激你的帮助和你的时间。谢谢你。


※感谢所有编辑我帖子的人。它帮助并将帮助我改进我的帖子。


慕斯709654
浏览 139回答 2
2回答

拉丁的传说

首先,您只能得到n带有的第一行itertools.islice,然后写下这些行:from itertools import islicen = 10with open('a.txt', 'r') as infile, open('b.txt', 'w') as outfile:&nbsp; &nbsp; first_lines = islice(infile, n)&nbsp; &nbsp; outfile.writelines(first_lines)

叮当猫咪

我从Read large text files in Python, line by line without loading it in memory的接受答案中抓住了这个:with open("log.txt") as infile:&nbsp; &nbsp; for line in infile:&nbsp; &nbsp; &nbsp; &nbsp; do_something_with(line)现在,适用于您的具体问题:def grab_lines(in_path, out_path, start, end):&nbsp; &nbsp; with open(out_path, "w") as outfile:&nbsp; &nbsp; &nbsp; &nbsp; counter = -1&nbsp; &nbsp; &nbsp; &nbsp; with open(in_path) as infile:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for line in infile:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter += 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if counter < start:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elif start <= counter <= end:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outfile.write(line)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python