在Python中将.txt文件分成多个部分

2024-04-16 22:15:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的乞丐,我有一个关于文件读取的问题: 我需要处理一个文件中的信息写入另一个。我知道怎么做,但这对我的电脑来说真的是一个很大的资源消耗,因为文件很大,但我知道它的格式! 文件格式如下:

4 13
9 3 4 7
3 3 3 3
3 5 2 1

我不会解释它的用途,因为它会花很多时间,也不会很有用,但是这个文件基本上是由四行组成的,一次又一次。为了转换一个很长的文件:

inputfile = open("input.txt", "r")
output = open("output.txt", "w")
Chain = inputfile.read()
Chain = Chain.split("\n")
Chained = ' '.join(Chain)
Chain = Chained.split(" ")
Chain = list(map(int, Chain))

后来,我只是用“任务ID”来处理它,但我觉得它真的没有效率。 所以你知道我如何把链分成多个,知道它们是如何格式化的吗? 感谢阅读!你知道吗


Tags: 文件txt信息chainoutput格式资源open
3条回答

嗯,我相信有一种方法可以在不读取文件的情况下写入文件

Add text to end of line without loading file

https://docs.python.org/2.7/library/functions.html#print

from __future__ import print_function
# if you are using python2.7
i = open("input","r")
f = open("output.txt","w")
a = "awesome"
for line in i:
    #iterate lines in file input
    line.strip()
    #this will remove the \n in the end of the string
    print(line,end=" ",file=f) 
    #this will write to file output with space at the end of it

这可能会有帮助,我也是一个新手,但有更好的谷歌fuxd

也许一行一行地做。这样它消耗更少的内存。你知道吗

inputfile = open("input.txt", "r")
output = open("output.txt", "a")

while True:
    line = inputfile.readline()
    numbers = words.split(" ")
    integers = list(map(int, numbers))

    if not line: 
       break

单词中可能有一个换行符\n。还应该用空字符串替换它。你知道吗

怎么样:

res = []
with open('file', 'r') as f:
  for line in f:
    for num in line.split(' '):
      res.append(int(num))

不是把整个文件读入内存,而是一行一行地读。 这有用吗?你知道吗

如果你需要一次走4行,只需添加一个内部循环。你知道吗

关于输出,我假设你想对输入做一些计算,所以我不一定在同一个循环中做。读取完成后处理输入,或者不使用列表,而是使用队列,并在该线程向其写入时从队列中读取另一个线程。你知道吗

也许列表理解的效用也会有所帮助(我怀疑这是否会产生影响):

res = []
with open('file', 'r') as f:
  for line in f:
    res.append( int(num) for num in line.split() )

相关问题 更多 >