Python从文件读取行并从特定行号写入另一个文件

时间:2016-10-17 13:39:25

标签: python file

我想从文件中读取行并从特定行号写入另一个文件。我有这个脚本,它写入所有读取行。我需要跳过前四行并将其余内容写入另一行。有什么想法吗?

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()

1 个答案:

答案 0 :(得分:4)

itertools.islice is designed for this

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))

如果您需要随时处理这些行,请跳过writelines并返回:

    for line in itertools.islice(f1, 4, None):
        ... do stuff with line ...
        f2.write(line)

无论哪种方式,你甚至都看不到前四行(Python正在阅读它们并无缝地丢弃它们。)