【发布时间】:2018-04-29 13:05:38
【问题描述】:
我需要编写一个包含 7000 多行文本文件的代码。我需要每隔 10 行拆分一次并将其写入另一个文件。
【问题讨论】:
-
为什么要编写一个python脚本来做到这一点?看linux.die.net/man/1/split
标签: python python-3.x file-handling
我需要编写一个包含 7000 多行文本文件的代码。我需要每隔 10 行拆分一次并将其写入另一个文件。
【问题讨论】:
标签: python python-3.x file-handling
with open(fname) as f:
content = f.readlines()
with open(fname) as g:
len_f = len(content)
for x in xrange(0, len_f):
if x % 10 = 0:
g.write(content[x])
g.write("\n") #For new-line
else:
pass
g.close()
f.close()
应该工作! (Python 2.x)
要点:
1) 写完每一行后不要打开/关闭写文件。
2) 完成后关闭文件。
【讨论】:
打开文件,然后遍历输入行,每 10 行写入输出文件:
with open(in_name, 'r') as f:
with open(out_name, 'w') as g:
count = 0
for line in f:
if count % 10 == 0:
g.write(line)
count += 1
open()context manager 将在退出范围时关闭文件。
由于输出的决定只是简单地计数,因此您可以使用切片 f.readlines()[::10]
虽然如果文件很大,itertools islice 生成器可能更合适。
from itertools import islice
with open(in_name, 'r') as f:
with open(out_name, 'w') as g:
g.writelines( islice(f, 0, None, 10) ):
我读到你的问题是想每 10 行写一次。如果要写入包含 10 个文件块的大量文件,则需要循环直到输入文件用完。这与显示为重复的问题不同。如果分块读取超过文件末尾,则该答案会中断。
from itertools import islice, count
out_name = 'chunk_{}.txt'
with open(in_name) as f:
for c in count():
chunk = list(islice(f, 10))
if not chunk:
break
with open(out_name.format(c)) as g:
g.writelines(chunk)
【讨论】: