[英]Python read lines from a file and write from a specific line number to another file
I want to read the lines from a file and write from a specific line number to another file. 我想从文件中读取行,并从特定的行号写入另一个文件。 I have this script, which writes all the read lines.
我有这个脚本,它写入所有读取的行。 I need to skip the first four lines and write the rest to another fils.
我需要跳过前四行,并将其余的写到另一个文件。 Any ideas?
有任何想法吗?
for k in range (0,16):
print 'k =',k
from abaqus import session
k=k+1
print k
f1 = open('VY_NM_VR_lin_o1_bonded_results_{k}.txt'.format(k=k))
#with open('VY_{k}'.format(k=k), 'a') as f1:
lines = f1.readlines()
for i, line in enumerate(lines):
#print i
print(repr(line))
#if line.startswith(searchquery):
f2.write(line)
#f2.write('%s'%listc + "\n")
i = i+1
#else :
# i = i+1
#os.close(f1)
f1.close()
f2.close()
itertools.islice
is designed for this : itertools.islice
为此目的而设计 :
import itertools
with open('VY_NM_VR_lin_o1_bonded_results_{k}.txt'.format(k=k)) as f1:
# islice w/4 & None skips first four lines of f1, then generates the rest,
# and writelines can take that iterator directly to write them all out
f2.writelines(itertools.islice(f1, 4, None))
If you need to process the lines as you go, then skip writelines
and go back to: 如果您需要在处理过程中处理行,则跳过
writelines
并返回到:
for line in itertools.islice(f1, 4, None):
... do stuff with line ...
f2.write(line)
Either way, you never even see the first four lines (Python is reading them and discarding them for you seamlessly). 无论哪种方式,您都不会看到前四行(Python正在读取它们并为您无缝地丢弃它们)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.