繁体   English   中英

从文件中读取特定行并在python中写入另一个文件

[英]Reading specific lines from a file and writing to another file in python

我有一个包含1000行的文件。 前15行将是标题信息。

我正在尝试执行以下操作:

1)读取文件2)获取带有标题信息的行数。 它将返回15 3)将第1-15行写入文本文件。

我能够正确执行1和2,但不能执行第三步。 有任何输入吗?

下面是我的代码

#!/usr/bin/python
import numpy;
import os; 
import math;
import cPickle; import time
from numpy import arange, sign
import copy
import re 
import sys  
import string
import mmap
head_lines = 0;
count=1
fide = open("text1.txt","r");
while (count==1):  #We skip header
   head_lines = head_lines+1;
   line = fide.readline();
   if 'END OF HEADER' in line:
    print 'End of the Header reached'
    break
print "hello world"
print head_lines
nlines = head_lines;
key=1;
while (key < nlines):
 file1 = open("Header.txt","w")
 lines = fide.readline()
 file1.write(lines)
 key = key+1;
print "done"
with open("input.txt") as f1:
   with open("output.txt","w") as f2:
        for _ in range(15):
            f2.write(f1.readline())

这是您要的吗?

(在python2.7中,我认为您可以将with open('f1') as f1,open('f2','w') as f2: ...

您的代码中有两个问题:

  1. 无论您在header.txt文件中写入的内容是什么,每次重新循环时都将其覆盖while因为您要重新打开文件,这会将文件指针指向其起点,即文件的开头。
  2. 第二个问题是相似的,但在另一个方面是fide 您将其打开,将文件指针指向文件的开头,并读取一行直到标题的末尾。 而在第二while循环你把从同一个文件指针读取行fide ,所以你正在阅读的未来nlines

您可以将标题的行存储在列表中,然后将这些字符串写入输出文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM