zoukankan      html  css  js  c++  java
  • 文件操作

    文件操作模式 :

    • 只读模式 r  
      f=open('a.txt','r',encoding='utf-8')

             不写时默认是r模式。可读不可写。

    • 只写模式 w
      f=open('a.txt','w',encoding='utf-8')

            可写不可读,写时会将原始内容清空。

    • 追加模式 a
      f=open('a.txt','a',encoding='utf-8')

            可写不可读,写时不会清空原来的内容。

    • r+
      f=open('a.txt','r+',encoding='utf-8')#写在前面
    • w+
      f=open('a.txt','w+',encoding='utf-8')

       读时不会报错,但是读不到东西,会清空文件内容。

    • a+
      f=open('a.txt','a+',encoding='utf-8')

       最好使得方法,可读可写。

        r、r+打开不存在的文件都会报错,其它的模式会自动创建。

    读文件:

    result = f.read()#读所有东西
    result = f.readlines()#['abc
    ', 'hjhsj
    ', '中文
    ', 'hsuhsush
    ', '133434
    ', 'ghsduwhue']
    result = f.readline()#读一行

    写文件:

    f.write('tzy')
    f.writelines('gygyg')#可写列表,可写可循环的东西
    f.writelines(['q','2'])#可写列表,可写可循环的东西,不可写数字

    关闭文件:

    f.close()

    文件指针:

    f.seek(0)

    例子:

    #每个在文件中占一行
    names = ['小红','小绿','jshjddh'] names = ' '.join(names) f.writelines(names)
    #将数字写入文件 l
    = [1,2,3,4] for i in range(len(l)): l[i] = str(l[i]) print(l) f.writelines(l)

    清空文件内容:

    f.truncate()#清空文件内容

     大文件处理:

    #大文件内容修改,直接循环文件,一行一行修改,修改完一行就放到新文件中,最后将旧文件删除,新文件重命名成原文件
    with open('words.txt',encoding='utf-8') as fr,open('words_new.txt','w',encoding='utf-8') as fw:
        for line in fr:
            line = line.strip()
            if line:
                line = line.upper()
                fw.write(line+'
    ')
    import os
    os.remove('words.txt')
    os.rename('words_new.txt','words.txt')
    with open('user.txt','a+',encoding='utf-8') as f:#文件对象,文件句柄
        f.seek(0)
        # result = f.read()
        # print(result)
        for line in f:#处理大文件,直接循环文件
            line = line.strip()
            if line:
                print(line)

     文件操作练习:

    监控日志,找出每分钟请求大于200次的ip

    #1、监控日志,找到每分钟请求大于200次的ip加入黑名单
    import time
    point = 0
    while True:
        ips = {}
        with open('access.log',encoding='utf-8') as f:
            f.seek(point)
            for line in f:
                line = line.strip()
                if line:
                    ip = line.split()[0]
                    if ip in ips:
                        ips[ip]+=1
                    else:
                        ips[ip]=1
            point = f.tell()#记录当前指针位置
            for ip in ips:
                count = ips[ip]
                if count>=200:
                    print('%s请求了%s次'%(ip,count))
            time.sleep(60)
  • 相关阅读:
    jni基础
    Rank Scores
    LeetCode:Longest Substring Without Repeating Characters
    LeetCode: Two Sum
    vim配置
    设计模式眨一眨
    分布式时序数据库InfluxDB
    地图坐标转换
    根据两点间的经纬度计算距离
    解密经纬度数据(火星坐标)
  • 原文地址:https://www.cnblogs.com/Mezhou/p/13546582.html
Copyright © 2011-2022 走看看