2017-09-16 173 views
1

我有兩個要求。閱讀python文件的最後一行

第一個要求 - 我想讀取文件的最後一行,並將最後一個值賦給python中的變量。

第二個要求 -

這裏是我的示例文件。

<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/> 
<context:property-placeholder location="filename.txt"/> 

從這個文件我想讀的內容即FILENAME.TXT這將是後<context:property-placeholder location= .。並希望該值分配給蟒蛇的變量。

+0

參見[閱讀以相反的順序使用python文件(工作https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python#23646049) – jq170727

回答

2

爲什麼你只是讀取所有行並將最後一行存儲到變量?

f_read = open("filename.txt", "r") 
last_line = f_read.readlines()[-1] 
f_read.close() 
-1

你可以閱讀和編輯所有行做這樣的事情:

file = open('your_file.txt', 'r') 
read_file = file.readlines() 
file.close() 

file1 = open('your_file.txt', 'w') 

var = 'filename.txt' 

for lec in range(len(read_file)): 
    if lec == 1: 
     file1.write('<context:property-placeholder location="%s"/>' % var) 
    else: 
     file1.write(read_file[lec]) 
file1.close() 
+0

感謝您的回覆。 。它會在當前目錄下創建一個新文件(filename.txt)。如果是,我不想在當前目錄中創建一個新文件。 – techi

+0

爲你工作? –

+0

感謝您的回覆。 。它會在當前目錄下創建一個新文件(filename.txt)。如果是,我不想在當前目錄中創建一個新文件。 – techi

1

他不只是詢問如何讀取文件中的行,或如何讀取的最後一行到一個變量。他還問如何從最後一行解析出包含目標值的子字符串。

這是一種方法。這是最短的路嗎?不,但如果你不知道如何分割字符串,你應該先學習這裏使用的每個內置函數。此代碼會得到你想要的東西:

# Open the file 
myfile = open("filename.txt", "r") 
# Read all the lines into a List 
lst = list(myfile.readlines()) 
# Close the file 
myfile.close() 
# Get just the last line 
lastline = lst[len(lst)-1] 
# Locate the start of the label you want, 
# and set the start position at the end 
# of the label: 
intStart = lastline.find('location="') + 10 
# snip off a substring from the 
# target value to the end (this is called a slice): 
sub = lastline[intStart:] 
# Your ending marker is now the 
# ending quote (") that is located 
# at the end of your target value. 
# Get it's index. 
intEnd = sub.find('"') 
# Finally, grab the value, using 
# another slice operation. 
finalvalue = sub[0:intEnd] 
print finalvalue 

打印命令的輸出應該是這樣的:這裏介紹

filename.txt 

主題:

  • 讀取文本文件
  • 製作一個Python內容中的行列表,以便使用基於零的索引len(List) -1輕鬆獲取最後一行。
  • 使用find得到一個字符串的索引位置字符串
  • 內使用slice獲得子

所有這些主題是Python的文檔中 - 沒有什麼額外的這裏,並且不需要進口使用這裏使用的內置函數。

乾杯,
- =卡梅倫

1

在擁有tail指揮系統,你可以使用tail,這對於大文件會緩解你的閱讀整個文件的必要性。

from subprocess import Popen, PIPE 
f = 'yourfilename.txt' 
# Get the last line from the file 
p = Popen(['tail','-1',f],shell=False, stderr=PIPE, stdout=PIPE) 
res,err = p.communicate() 
if err: 
    print (err.decode()) 
else: 
    # Use split to get the part of the line that you require 
    res = res.decode().split('location="')[1].strip().split('"')[0] 
    print (res) 

注:decode()命令僅需要python3

res = res.split('location="')[1].strip().split('"')[0] 

將爲python2.x