Python之 文件操作

1、打开文件

f=open('hello.txt','a+')   #打开‘hello.txt’文件
#r  只读模式,打开的文件不存在的话,会报错
#w  只写模式,会清空原来文件的内容
#a+ 追加模式 打开的文件不存在,会新建一个文件

2、读写文件

f=open('hello.txt','a+')
f.write('joly,123\npop,456')
#f.seek(0)
print(f.read())  #获取到文件里的所有内容  
#执行这个发现没有结果?原来在文件写完内容以后,文件指针挪到了最后,后面没内
#容,自然没有东西  这个时候引入文件只针对概念f.seek(0),就是把文件指针挪到开头
#然后就读出东西了

f=open('hello.txt','a+')
print(f.readlines())#以列表的形式展示出来

f=open('hello.txt','a+') 
print(f.readline()) #显示指针所在那一行的数据

inf=['uiui,890\n','hhh,009\n']
f.writeable(inf)  #把列表写进文件里
f.write() #如果写字符串的话,就直接用write就好


#r,w,a+这三种模式以外,还有r+ w+ 
f=open('hello.txt','r+')
f.write('wwww,123') #r+模式,打开不存在的文件还是会报错,写的东西显示在文件首

f=open('hello.txt','w+')
f.write #还是会清空文件,读出来的东西是空,因为文件清空没内容,很鸡肋,不推荐


#打开非文本文件,参数要加b  如rb  wb

3、高效处理文件
如果文件过大,最后一行一行读,提高效率

#第一种方式:
f=open('hello.txt',encoding='utf-8')
while true:
    line=f.readline()
    if line!='':
        print(line)
    else:
        print('文件内容读完了')
        break


#第二种方式:
for i in f:
    print(i)

写一个花式操纵文件的题
1、要从日志里面找到1分钟之内访问超过200次的
2、每分钟都运行一次
3、超过200次的加入黑名单
思路:
1、读取文件内容,获取到ip地址
2、把每个ip地址存起来 {}
3、判断ip访问的次数是否超过200次
4、加入黑名单 print

import time
point = 0 #初始的位置
while True:
    ips = {}
    f = open('access.log',encoding='utf-8')
    f.seek(point)
    for line in f: #循环取文件里面每行数据
        ip = line.split()[0] #按照空格分割,取第一个元素就ip
        if ip in ips:#判断这个ip是否存在
            # ips[ip] = ips[ip]+1
            ips[ip]+=1#如果存在的话,次数加+1
        else:
            ips[ip]=1 #如果不存在ip的次数就是1
    point = f.tell() #记录文件指针位置
    f.close()
    for ip,count in ips.items():#循环这个字典,判断次数大于200的
        if count>=200:
            print('%s 加入黑名单'%ip)
    time.sleep(60)

3、修改文件

f = open('C:\Users\nhy\Desktop\file.txt',encoding='utf-8')    #错的
f = open(r'C:\Users\nhy\Desktop\file.txt',encoding='utf-8')  #对的

#文件如果写的是绝对路径,如上图,容易有\n这种错误,这个时候,要写r'绝对路径'
#第一种方式:
f = open('file.txt',encoding='utf-8')
t = f.read().replace('一点','两点')
f.close()   #先替换
f = open('file.txt',mode='w',encoding='utf-8')  #用w模式,删除原文件f.write(t)   #写入新文件
f.flush()   #立即把缓冲区里面的内容,写到磁盘上
f.close() 


f = open('file.txt','a+',encoding='utf-8')
f.seek(0)
res = f.read().replace('你','NI')
f.seek(0)
f.truncate()  #清空文件里的内容
f.write(res)
f.close()  


import os  #导入模块
f = open('file.txt',encoding='utf-8')
f2 = open('cpfile.txt','w',encoding='utf-8')  
for line in f:
    new_line = line.replace('两点','yi点')
    f2.write(new_line)
f.close()
f2.close()
os.remove('file.txt')  #删除原文件
os.rename('cpfile.txt','file.txt')  #给新文件改名

import os  #如果嫌关闭文件麻烦,可以用我with  as这个关键字
with open('file.txt',encoding='utf-8') as f,    open('file.txt.bak','w',encoding='utf-8') as f2:
for line in f:
    new_line = line.replace('二点','一点')
    f2.write(new_line)
os.remove('file.txt')
os.rename('file.txt.bak','file.txt')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值