[英]Extracting values from text file
我有一個文本文件如下,有2列
44333373 -5.829738285
3007762 -5.468521083
16756295 -5.247183569
46197456 -5.216096421
46884567 -5.195179321
44333390 -5.162411562
44420579 -5.133122186
6439190 -5.028260409
...
我想提取大於-5.162411562理想輸出的值
產量
44333373 -5.829738285
3007762 -5.468521083
16756295 -5.247183569
46197456 -5.216096421
46884567 -5.195179321
為了完成這個任務,我編寫了簡單的python腳本
f1=open("file.txt","r")
n=0
for line in f1.readlines():
if float(n) > -5.162411562:
print line
但它只是讀取文件中的所有數據。 我知道這是一項非常簡單的任務,但我無法弄清楚我哪里出錯了。 有人可以幫忙嗎?
好吧,你需要實際將n
設置為零以外的值。 怎么樣:
with open('file.txt') as f1:
for line in f1: # readlines is not necessary here
n = float(line.split()[1]) # line.split()[0] is the first number
if n > -5.162411562:
print (line.rstrip('\r\n')) # rstrip to remove the existing EOL in line
line
包含44333373 -5.829738285
。 當循環通過lines
你需要分割線並考慮第一個元素而你不需要n
。 然后比較。 所以代碼改為 -
f1=open("file.txt","r")
for line in f1.readlines():
if float(line.split()[1]) > -5.162411562:
print line
這里稍作修改。 readlines
一次性將整個文件內容讀入內存。 如果文件太大,那么你可能會遇到問題。 python中的文件操作符是一個迭代器。 多么酷啊! 也open
在默認情況下打開一個文件read
模式。 所以代碼進一步簡化為 -
for line in open('file.txt'):
if float(line.split()[1]) > -5.162411562:
print line
希望這可以幫助...
您提供的代碼的問題是n
的值永遠不會更改,因此if
語句將始終計算為True
,因此將打印該line
:
f1=open("file.txt","r")
n=0 # the `n` is set here
for line in f1.readlines():
if float(n) > -5.162411562: # `n` is always `0`, so this is always `True`
print line
您需要使用從每行第二列提取的數字更新變量n
。
此外, if
條件必須將其比較運算符從>
(大於)更改為<
(小於),因為您在輸出中顯示的值是“小於-5.162411562”的值,而不是“大於”
而且,應該注意,不一定需要n=0
。
通過這些更改,我們得到以下代碼:
f1 = open("file.txt","r")
for line in f1.readlines():
n = line.split()[1] # get the second column
if float(n) < -5.162411562: # changed the direction comparison
print line.rstrip() # remove the newline from the line read
# from the file to prevent doubling of newlines
# from the print statement
f1.close() # for completeness, close the file
結果輸出是:
44333373 -5.829738285
3007762 -5.468521083
16756295 -5.247183569
46197456 -5.216096421
46884567 -5.195179321
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.