[英]Moving each value of a text file to its own line in Python
lines = open("textfile").read().split()
That will split the whole file in parts using blanks (spaces, tabs, etc) as the separator. 这将使用空格(空格,制表符等)作为分隔符将整个文件分成几部分。 If you want to save it again to a file, each one on a line:
如果要再次将其保存到文件中,请每行一行:
open("newtextfile", "w").write('\n'.join(lines))
Looking at your file makes me think that you want the last trade times to be kept together, eg 查看您的文件,我认为您希望将最后交易时间保持在一起,例如
0.00000159
volume
645453536.89920200
lasttradetime
2014 03 06 10 32 03
So I'd recommend something like 所以我建议像
import re
with open("infile.txt") as fp_in, open("outfile.txt", "w") as fp_out:
d = fp_in.read()
parts = re.split(r"\s\s+", d)
for part in parts:
fp_out.write(part + "\n")
which will achieve that. 这将实现这一目标。 (Probably be marginally faster to combine the parts and do one write, like
"\\n".join(parts) + "\\n"
.) (合并这些部分并执行一次写操作可能稍快一些,例如
"\\n".join(parts) + "\\n"
。)
To support arbitrary large files that might not fit in memory, you could use mmap
: 要支持可能不适合内存的任意大文件,可以使用
mmap
:
#!/usr/bin/env python
import re
from mmap import ACCESS_READ, mmap
with open('filename', 'rb') as file:
mm = mmap(file.fileno(), 0, access=ACCESS_READ)
try:
with open('output', 'wb') as output_file:
for m in re.finditer(r'\S+', mm):
print >>output_file, m.group()
finally:
mm.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.