Disadvantage of introducing the issue, absolute path
In python learning, I will put the code under the code directory, and other types of files in the res directory, easy to navigate and manage.
But I would like to call 404.py access.log under res directory under the code directory, using an absolute path is long ( C: \ the Users \ Administrator \ Desktop \ Day \ JASN-70-Days \ Day01 ~ 15 \ Day 09 \ code \ the access.log ), and folder location on the path of movement once an error occurs.
Relative path appearances
r'../res/access.log'
That can be the perfect solution to this problem.
Therefore, the revised code as follows:
'''
模拟管道,实现功能:tail -f access.log | grep '404'
version:01
author:jasn
Date:2020-01-09
'''
import time
def tail(filepath):
with open(filepath,'rb') as f:
f.seek(0,2) #获取最后一行
while True:
line=f.readline()
if line:
yield line
else:
time.sleep(0.5) #定时间隔刷新
def grep(pattern,lines):
for line in lines:
line=line.decode('utf-8')
if pattern in line:
yield line
for line in grep('404',tail(r'../res/access.log')):
print(line,end='')
#写入内容
with open(r'../res/access.log','a',encoding='utf-8')as f:
f.write('出错了,404!\n')
Use relative path python
| -- code
| -- conf.py
| -- start.png
| -- res
|config.txt
|access.log
| -- main.py
| --logo.png
in casemain.pyReferenceslogo.png, Relative path of the wording:"./logo.png". logo.png and main.py in the same directory
ifconf.pyReferencesaccess.log, Relative path of the wording:"…/res/access.log"
in caseconf.pyReferenceslogo.png, Relative path of the wording:"…/logo.ong"
. File refers to the current file folder
… It refers to the parent directory of the current file.
Of course, the relative path may also be expressed on a higher level, the higher the upper, the upper parent directory and the like
on the upper: ... / ... /
On the higher level: ... / ... / ... /
On the upper superior: ... / ... / ... / ... /
relative path may also represent different subdirectories and files in the parent directory, for example:
... / ... / Day09 / code / test.txt: represents the code directory under Day09 directory under the parent directory of the current file inside the test.txt file