如何使用python从txt文件中每隔10行选取一行?
我需要写一个代码,我有巨大的7000多行的文本文件。我需要每10行拆分一行,然后将其写入另一个文件如何使用python从txt文件中每隔10行选取一行?,python,python-3.x,file-handling,Python,Python 3.x,File Handling,我需要写一个代码,我有巨大的7000多行的文本文件。我需要每10行拆分一行,然后将其写入另一个文件 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
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()
将关闭文件
由于输出的决定是简单的计数,因此可以使用切片f.readlines()[::10]
虽然如果文件很大,生成器可能更合适
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个文件块的文件,你需要循环直到输入文件用完。这与显示为重复的问题不同。如果分块读取超过文件末尾,则该答案将中断
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)
可能重复-为什么要编写python脚本来实现这一点?看看