[英]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 :-
我正在尝试执行以下步骤:
line.split()[-2]
string. line.split()[-2]
字符串。 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.