tec*_*chi 3 python python-2.7 python-3.x python-requests
我有两个要求.
第一个要求 - 我想读取文件的最后一行,并将最后一个值赋给python中的变量.
第二要求 -
这是我的示例文件.
<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/>
<context:property-placeholder location="filename.txt"/>
Run Code Online (Sandbox Code Playgroud)
从这个文件我想读取内容,即filename.txt将在之后<context:property-placeholder location= ..并希望将该值赋给python中的变量.
Jaz*_*man 15
正如许多其他人所说,对于大文件,任何不查找末尾或从文件末尾开始的方法都是非常低效的。不过,最佳答案的搜索方法很棒。如果其他人正在寻找一种读取文件的第 n 行到最后一行的解决方案,这里是我写的一个。对于大型文件也非常快速和高效(网络上 7GB 文件需要不到 1 毫秒)。
def read_n_to_last_line(filename, n = 1):
"""Returns the nth before last line of a file (n=1 gives last line)"""
num_newlines = 0
with open(filename, 'rb') as f:
try:
f.seek(-2, os.SEEK_END)
while num_newlines < n:
f.seek(-2, os.SEEK_CUR)
if f.read(1) == b'\n':
num_newlines += 1
except OSError:
f.seek(0)
last_line = f.readline().decode()
return last_line
Run Code Online (Sandbox Code Playgroud)
小智 7
为什么你只读取所有行并将最后一行存储到变量?
f_read = open("filename.txt", "r")
last_line = f_read.readlines()[-1]
f_read.close()
Run Code Online (Sandbox Code Playgroud)
在具有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)
Run Code Online (Sandbox Code Playgroud)
对于通用的whole last line:
res = res.decode()
print(res)
Run Code Online (Sandbox Code Playgroud)
要调整行数,请更改tail命令。
对于最后 10 行,您将使用['tail','-10',f]
从第 N 行到末尾:['tail','-n+10000',f]
其中 10,000 是您要读取的行
注意:该decode()命令仅适用于python3
res = res.split('location="')[1].strip().split('"')[0]
Run Code Online (Sandbox Code Playgroud)
会为python2.x
一个简单的解决方案,不需要将整个文件存储在内存中(例如,使用file.readlines()或等效结构):
with open('filename.txt') as f:
for line in f:
pass
last_line = line
Run Code Online (Sandbox Code Playgroud)
对于大文件,查找文件末尾并向后移动以找到换行符会更有效,例如:
import os
with open('filename.txt', 'rb') as f:
f.seek(-2, os.SEEK_END).
while f.read(1) != b'\n':
f.seek(-2, os.SEEK_CUR)
last_line = f.readline().decode()
Run Code Online (Sandbox Code Playgroud)
来自https://docs.python.org/3/library/collections.html的示例
from collections import deque
def tail(filename, n=10):
'Return the last n lines of a file'
with open(filename) as f:
return deque(f, n)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8347 次 |
| 最近记录: |