Day4 - 文件操作
一、解包
解包适用于有下标的数据类型
原代码:
msg = "admin,123456"
username = msg.split(',')[0]
password = msg.split(',')[1]
print(username + '\n' + password)
[result~]:
admin
123456
使用解包方法:
msg = "admin,123456"
username,password = msg.split(',') # 解包
print(username + '\n' + password)
[result~]:
admin
123456
1.使用解包的方法处理列表:
l = [1,2,'a','c',3]
print(l[0],l[1])
e,f,g,h,i = l
print(str(e) + str(f) + str(g) + str(h) + str(i))
[result~]:
1 2
12ac3
2.使用解包的方法处理元组:
l2 = (1,2,3)
a,b,c = l2
print(a,b,c)
[result~]:
1 2 3
items()方法是将字典转换为元组,再采用解包的方法进行
d = {"username":"admin","password":"123456"}
print(d.items())
for k,v in d.items():
print(k,v)
[result~]:
dict_items([('username', 'admin'), ('password', '123456')])
username admin
password 123456
3.使用解包的方法处理字符串
l3 = 'abc'
a,b,c = l3
print(a,b,c)
[result~]:
a b c
二、文件操作
1.“r+” 读写模式
a.r相关如果文件不存在会报错
b.文件指针在最前面
先写后读,可以验证出指针在最前面,新加入内容会替换原来的内容
原文件,pw.txt:
12345678901234567890nmmmdas
admin,123
f = open('pw.txt','r+',encoding="utf-8") # 写的时候报错
f.write("要完成")
print(f.read())
f.close()
[result~]:
01234567890nmmmdas
admin,123
运行程序之后的文件,pw.txt:
要完成01234567890nmmmdas
admin,123
先写后读,读完成后指针移动到最后,并且将需要写的内容添加在最后
原文件,pw.txt:
12345678901234567890nmmmdas
admin,123
f = open('pw.txt','r+',encoding="utf-8") # 写的时候报错
print(f.read())
f.write("要完成")
f.close()
[result~]:
12345678901234567890nmmmdas
admin,123
运行程序之后的文件,pw.txt:
12345678901234567890nmmmdas
admin,123要完成
2.“w+” 写读模式
和“w”相关的操作,都会创建文件,都会清空文件内容
原文件,pw.txt:
12345678901234567890nmmmdas
admin,123要完成
f = open('pw.txt','w+',encoding="utf-8")
print(f.read())
f.close()
[result~]:
输出为空,且原文件也被该为空
正确使用方法:(先写,将指针指向0,在进行读)
f = open('pw.txt','w+',encoding="utf-8")
f.write("abcdefghijklmnopqrstuvwxyz")
f.seek(0)
print(f.read())
f.close()
3.“a+” 追加读模式
与“a”相关,如果要读,那么就要将指针移动到首位
即使将指针移动到首位,追加的内容也会添加在最后
原文件pw.txt:
abcdefghijklmnopqrstuvwxyz1234567890
f = open('pw.txt','a+',encoding="utf-8")
f.seek(0)
print(f.read())
f.write("加快速度")
f.close()
[result~]:
abcdefghijklmnopqrstuvwxyz1234567890
执行脚本之后的文件,pw.txt:
abcdefghijklmnopqrstuvwxyz1234567890加快速度
加上"b"即和二进制文件有关
4.rb
5.wb
6.ab
7.多行文件操作
如果需要读取文件的每行内容,open()默认的操作文件模式应改为"r"
f = open('pw.txt',encoding='utf-8')
for line in f:
print(line)
f.close()
8.flush()立刻将文件内容写到磁盘中
9.tell()输出指针目前所在位置
三、修改文件内容
打开固定路径文件,并将""取消特殊含义的两种方法:
1.f = open(‘F:\飞马座_Python\Mycode\day4\user.txt’,‘w’,encoding=‘utf-8’)
2.f = open(r’F:\飞马座_Python\Mycode\day4\user.txt’,‘w’,encoding=‘utf-8’) # r 代表原字符
第一种方式:
使用 “r"和"w” 方法,并使用replace方法进行替换,需要打开文件两次
f = open('F:\\飞马座_Python\\Mycode\\day4\\user.txt','r',encoding='utf-8')
简单但多次打开的方法
result = f.read()
print(result)
f.close()
new_result = result.replace("hello","您好")
f = open("user.txt",'w',encoding="utf-8")
f.write(new_result)
f.close()
第二种方式
使用"a+"的方式,并使用replace方法进行替换,并使用truncate()方法将文件清空,“a+”默认指针在违建的尾部,需要将指针移动到开头
# 打开一次的方法,使用‘a+’,'a+'默认指针在文件的尾部,需要将指针移动到开头
f = open('F:\\飞马座_Python\\Mycode\\day4\\user.txt','a+',encoding='utf-8')
f.seek(0)
result = f.read()
result_new = result.replace("您好","hello")
f.seek(0)
f.truncate() # 此方法用于清空文件
f.write(result_new)
f.close()
第三种方式
使用"a+"的方式,并使用replace方法进行替换,并使用truncate()方法将文件清空,不需要将指针移动到开头
打开一次的方法,使用‘r+’,'r+'默认指针在文件的尾部,不需要将指针移动到开头
f = open('F:\\飞马座_Python\\Mycode\\day4\\user.txt','r+',encoding='utf-8')
result = f.read()
result_new = result.replace("hello","你好")
f.seek(0)
f.truncate() # 此方法用于清空文件
f.write(result_new)
f.close()
第四种方式-以行为单位进行替换
import os
f1 = open('F:\\飞马座_Python\\Mycode\\day4\\user.txt',encoding='utf-8')
f2 = open("user.txt.new","w",encoding='utf-8')
for line in f1:
new_line = line.replace("周","周杰伦")
f2.write(new_line)
f1.close()
f2.close()
os.remove("user.txt")
os.rename("user.txt.new","user.txt")
四、自动关闭文件
使用with open() as f:方式
#自动关闭文件方法
with open(‘F:\飞马座_Python\Mycode\day4\user.txt’,encoding=‘utf-8’) as f:
f.read()
#同时打开两个文件
with open(‘user1.txt’,encoding=‘utf-8’) as f1, open(‘user2.txt’,encoding=‘utf-8’) as f2:
五、对文件、目录进行复制和删除
使用shutil模块中的copyfile()和copy()方法进行复制文件
copyfile()第二个参数需要加文件名或路径+文件名,但不可以只是路径
copy()第二个参数可以是文件名、路径、路径+文件名
copyfile()用法:
shutil.copyfile('passwords.txt', 'pd.txt')
shutil.copyfile('passwords.txt', '../day5/pd.txt')
shutil.copyfile('passwords.txt', '../day5/passwords.txt')
copy()用法:
shutil.copy('passwords.txt','new_pw.txt')
shutil.copy('passwords.txt','../day2')
shutil.copy('passwords.txt','../day2/passwords3.txt')
使用copytree()方法进行文件夹拷贝:
shutil.copytree('logs','logs2')
shutil.copytree('logs','../day1/logs') #当day1不存在时,会创建day1
删除非空文件夹rmtree()
os.rmdir() 只能删除非空文件夹
shutil.rmtree('logs') #慎用,此删除为彻底删除,无法找回
练习:监控日志分析
需求分析:
代码:
import time
point = 0
FILE_NAME = 'access.log'
while True:
ips = {}
f = open(FILE_NAME,encoding='utf-8')
f.seek(point)
if point == 0: # 判断是否为第一次读取
f.read() # 将指针移动到文件最后
else
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()
f.close()
for ip,count in ips.items():
if count>=50:
print("加入黑名单的ip是 %s " % ip)
time.sleep(60)
```