簡體   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