简体   繁体   English

只将所有分割行的一个字符串写入文件

[英]writing only the one string of all splitted lines to a file

I have a text file with around 80000 lines. 我有一个约有80000行的文本文件。 I am trying to do the following steps :- 我正在尝试执行以下步骤:

  1. I am trying to find lines based on its first character. 我试图根据其第一个字符找到行。 I am able to do that. 我能够做到。
  2. Now I am left with 7500 lines. 现在剩下7500行。
  3. I am splitting the lines and displaying its line.split()[-2] string. 我正在分割线并显示其line.split()[-2]字符串。
  4. I want to write those strings to a text file, and I am having difficulty with it. 我想将这些字符串写入文本文件,但遇到了困难。

Below is my code, can anybody figure out what am I doing wrong. 下面是我的代码,任何人都可以找出我在做什么错。

f4 = open("lines.txt")    #subroutine to find out number of intervals
for i in range(header_lines):
    for line in f4:
     with open("satsid.txt","w") as f5:
       if line.startswith(" 12"):
          print line.split()[-2]
          f5.write('line.split()[-2]')
          numints = numints+1;
       if not line:
           break      

Ignoring the loop over header_lines the following would replicate your code without re-opening the f5 file each time (which clears it each time you reopen): 忽略header_lines的循环,以下操作将复制您的代码,而无需每次都重新打开f5文件(每次重新打开时将其清除):

with open("lines.txt") as f4, open("satsid.txt","w") as f5:
    for line in f4:
        if line.startswith(" 12"):
            f5.write(line.split()[-2] + '\n')

This writes the 1-but-last element from the line to f5 if the line starts with ' 12' (a space, then a 1, then a 2). 如果该行以' 12' (一个空格,然后是1,然后是2)开头,则会将行中的1-but-last元素写入f5 I add a newline between these values in the output file. 我在输出文件中的这些值之间添加了换行符。

If you need to skip a number of lines (say a number stored in header_lines ) in f4 , use itertools.islice() to limit the loop: 如果您需要在f4跳过多行(例如,存储在header_lines中的header_lines ),请使用itertools.islice()来限制循环:

from itertools import islice

with open("lines.txt") as f4, open("satsid.txt","w") as f5:
    for line in islice(f4, header_lines, None):
        if line.startswith(" 12"):
            f5.write(line.split()[-2] + '\n')

islice() will skip over header_lines lines, then pass through the rest of the file until the end. islice()将跳过header_lines行,然后遍历文件的其余部分直到结尾。

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

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