在Python中分割多个部分的.txt文件
我是Python中的一个begginer,我有一个关于文件读取的问题: 我需要处理文件中的信息以将其写入另一个文件中。我知道如何做到这一点,但是对于我的电脑而言,它非常耗费资源,因为该文件非常大,但我知道它是如何格式化的! 文件遵循格式:在Python中分割多个部分的.txt文件
4 13
9 3 4 7
3 3 3 3
3 5 2 1
我不会解释什么是对的,因为它会采取年龄,不会是非常有用的,但文件essentialy由四大行这样的,一次再次。现在,我使用它来读取文件并将其转换在一个很长的链条:
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”对待它,但我觉得这是真的效率不高。 那么你知道我怎么可以将链分成多个知道它们是如何格式化? 感谢您的阅读!
如何:
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())
也许是一行一行。这样它消耗更少的内存。
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
。你还应该用空字符串替换它。
如果你不想消耗内存(可以如果文件非常大,则运行它),则需要逐行读取留置权。
with open('input.txt', 'w') as inputfile, open('"output.txt', 'w') as output:
for line in inputfile:
chain = line.split(" ")
#do some calculations or what ever you need
#and write those numbers to new file
numbers = list(map(int, chain))
for number in numbers
output.write("%d " % number)
嗯有写入到一个文件中的一些方法没有阅读它,我相信
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
这可能帮助,我是一个新手太多,但更好的谷歌富士XD
正是我在寻找的,谢谢! –