函数+文件
1. (其它)
1. 读取系统日志文件(如:360Tray.log)
(1)写一个函数,读取日志文件全部内容,并直接输出。
(2)写一个函数,读取日志文件全部内容,输出并以列表形式返回(每行一个列表项)。
(3)写一个函数,读取日志文件的前n行,不输出,直接返回。
(4)写一个函数,读取日志文件的从m行到n行。
2. 参考教材综合案例,完成一篇文章的词频统计(英文/中文)。文件可自行选择,也可使用如下附件。
(1)
f = open(r'D:\text.txt', encoding='utf-8')
txt = []
for line in f:
txt.append(line.strip())
print(txt)
(2)
f = open(r'D:\text.txt', encoding='utf-8') # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
(3)
def readlog(s):
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
a=f.read()
print(a)
def readlineslog(s):
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
ls = f.readline()
print(ls)
return ls
def tellPos(s, n):
if n == 0:
return 0
else:
c = 0
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
while 1:
line = f.readline()
c += 1
if c == n or line == '':
break
pos = f.tell()
return pos
def readlinelog(s, startline , endline):
pos = tellPos(s,startline)
c=0
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
f.seek(pos)
while 1:
line = f.readline()
c += 1
if c >= endline - startline or line == '':
break
s = r'D:\text.txt'
ls = readlinelog(s,0,6)#将0固定,更改结束值则可以实现要求
(4)
def readlog(s):
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
a=f.read()
print(a)
def readlineslog(s):
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
ls = f.readline()
print(ls)
return ls
def tellPos(s, n):
if n == 0:
return 0
else:
c = 0
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
while 1:
line = f.readline()
c += 1
if c == n or line == '':
break
pos = f.tell()
return pos
def readlinelog(s, startline , endline):
pos = tellPos(s,startline)
c=0
with open(s, 'r', encoding='utf-8', errors='ignore') as f:
f.seek(pos)
while 1:
line = f.readline()
print(line)
c += 1
if c >= endline - startline or line == '':
break
s = r'D:\text.txt'
ls = readlinelog(s,2,5)
print(ls)