python处理文件:

open()

help(open)

open(file,mode='r',encoding=None)

r

w 覆盖

x

a  追加

utf8  中文

file_name = r"E:\project0824\file01.txt"

创建文件对象,打开文件

fobj = open(file_name,mode="r")

content = fobj.read(10)

print(content)

fobj.close()

按行读取文件内容,针对日志,遍历

fobj = open(file_name,mode="r")

for line in fobj:

   print("---> %s" % line)

fobj.close()

另外一种,with关键字,操作执行完会自动关闭文件

with open(file_name,mode="r") as fobj:

    for line in fobj:

          print("---> %s" % line)


print(“文件是否关闭:”,fobj.closed)

set()  去重

data.count  统计次数


定义函数,统计web日志的用户访问量

web_log = r"E:\project\access.log"

def webUV():

   client_ip_list = []

   with open(web_log,mode="r") as fobj:

        for line in fobj:

            client_ip = line.split()[0]

            if client_ip != "::1"

               client_ip_list.append(client_ip)

            print(client_ip_list)

   for ip in set(client_ip_list):

        print("客户端地址: %s,访问此时:%s" % (ip,client_ip_list.count(ip)))

if __name__ == '__main__':

  webUV()

模块:xxx.py

import 模块名称

函数

test.py

def hello():

  print("hello world!!!")

if __name__ == '__main__':

   hello()


import test

test.hello()


会输出2次结果

加了if main 后只输出1次结果

如果被当成模块导入,测试代码不执行

import re

#使用正则在字符串中过滤数据,如果能过滤到,返回Match Object匹配对象,否则返回None

line = "123.117.34.38 - -  xxxxxx"

ip_regex = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'

is_match = re.search(ip_regex,line)

if is_match:

   print(“可以匹配数据”)

   ip = is_match.group()

   print(ip)

else:

   print(“未找到”)

re.search(is_match)


import re

def webUVxx():

   client_ip_list = []

   ip_regex = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'

   with open(web_log,mode="r") as fobj:

        for line in fobj:

           is_match = re.search(ip_regex,line)

           if is_match:

            client_ip = is_match.group()

               client_ip_list.append(client_ip)

            print(client_ip_list)

   for ip in set(client_ip_list):

        print("客户端地址: %s,访问此时:%s" % (ip,client_ip_list.count(ip)))

if __name__ == '__main__':

  webUVxx()