函数+文件(python版)

函数+文件

1. (其它)

1. 读取系统日志文件(如:360Tray.log)

(1)写一个函数,读取日志文件全部内容,并直接输出。

(2)写一个函数,读取日志文件全部内容,输出并以列表形式返回(每行一个列表项)。

(3)写一个函数,读取日志文件的前n行,不输出,直接返回。

(4)写一个函数,读取日志文件的从m行到n行。

2. 参考教材综合案例,完成一篇文章的词频统计(英文/中文)。文件可自行选择,也可使用如下附件。

novel.txt

人生.txt

(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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值