一、文件的读取
如果读取的是图片,音频,视频(非纯文本文件),需要通过读取二进制的方式读取和写入。
- 读取纯文本文件
r,r+,w,w+,a,a+ == rt,rt+wt,wt+,at,at+ - 读取二进制文件
rb,rb+,wb,wb+,ab,ab+
复制图片到另一张图片:
# 读取二进制文件的内容
f1 = open('hello.jpg',mode='rb')
content = f1.read()
f1.close()
f2 = open('happy.jpg',mode='wb')
# 写入要复制的文件的内容
f2.write(content)
f2.close()
-
文件操作的3步曲:打开—>操作---->关闭
r:
-默认参数
-只能读,不能写
-读取的文件不存在,会报错
w:
-写文件
-不能读文件
-会清空文件内容,并写入新的文件内容
-文件不存在的时候,会创建新的文件并写入内容
a:
-追加文件内容
-不会清空文件内容,会在文件的末尾追加内容
-文件不存在的时候,会创建新的文件并写入内容
-不能读文件
r+:能写能读,写会写在文件最前面w+:能写能读,但会清空原有内容,只保留写的新内容
a+:能追加能读,追加内容在文件的最后面
with open('/opt/passwd','w+') as f:
f.write('*****')
print(f.tell())
f.seek(0,0)
print(f.tell())
a=f.read()
print(a)
# 1.打开文件
f = open('/tmp/passwd', 'w+')
# 2.操作
print(f)
print(f.readable())
print(f.writable())#判断文件是否拥有写的权限
print(f.tell())#告诉当前文件指针所在的位置
print(f.read())
f.write('redhat')
f.read()
print(f.write('python'))
# 3.关闭
f.close()
**注意:**写完或者追加完,文件中的光标会移到末端,此时如果再读文件,首先需要把光标移到想要开始读的位置,比如;移到文件起始位置(f.seek(0,0)),然后再读取文件.
二、文件的三种读取方式及指针的移动
1.按行读取
print(f.readline()) #一次只能读取一行,适用于大文件的读取,读取返回一个字符串对象
如果想读取整个文件,则可以利用for循环:
import time
# 1.打开文件
f = open('/opt/passwd')
# 2.操作
f.seek(0,0)
while True:
a=f.readline()
print(a)
if len(a)==0:
break
# 3.关闭
f.close()
2.按字节读取
f = open('/opt/passwd')
f.seek(0,0)
print(f,read(5)) #读取前5个字节
f.close()
3.按行读取readlines
该方式读取返回一个列表,列表元素为文件的行内容
f = open('/opt/passwd')
f.seek(0,0)
print(f.readlines())
f.close()
如果想去掉每行后面的\n,怎么办?
法一:
f = open('/opt/passwd')
# 2.操作
f.seek(0,0)
line=f.readlines()
for i in line:
print(i.strip('\n'))
# 3.关闭
f.close()
法二:
f=open('/opt/passwd')
print([line.strip() for line in f.readlines()])
f.close()
法三:
f=open('/opt/passwd')
print(list(map(lambda x:x.strip(),f.readlines())))
f.close()
4.指针
seek():指针的移动
第一个参数:偏移量>0.向后移动,<0向前移动
第二个参数:0,移动到文件开头;1,当前位置;2,移动到文件末尾
三、上下文管理器
上下文管理器:打开文件,执行完with语句后,自动关闭文件。
#将第一个文件的内容写入第二个文件中
with open('/opt/file1') as f1,open('/opt/file2','w+') as f2:
f2.write(f1.read())
f2.seek(0,0)
print(f2.read())
注:file1里内容是11111,file2里内容是222222
牛刀小试:
练习1:
生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B,如:01-AF-3B-xx-xx-xx-xx
import random
import string
# print(string.hexdigits)
def creat_mac():
mac = '01-AF-3B'
# 生成16进制的数
hex_num = string.hexdigits
for i in range(3):
# 从16进制的字符串中随机选择两个数字
# 返回值是一个列表
n = random.sample(hex_num,2)
print(n)
# 拼接列表中的内容,将小写的字母转换成大写的字母
sn = '-' + ''.join(n).upper()
mac += sn
return mac
# 主函数 所记生成100个mac地址
def main():
with open('mac.txt','a') as f:
for i in range(100):
mac = creat_mac()
print(mac)
f.write(mac + '\n')
main()
生成的部分MAC码:
生成的文件:
打开生成的文件:
练习2:
京东二面编程题
- 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
- 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import random
def create_ip_file(filename):
ips = ['172.25.254.' + str(i) for i in range(1, 255)]
print(ips)
with open(filename, 'a+') as f:
for count in range(1200):
print(random.sample(ips, 1)) #产生的是列表形式
print(random.sample(ips, 1)[0])#取列表的第一个字符(),取出的形式没有双引号
f.write(random.sample(ips, 1)[0] + '\n')
create_ip_file('ips.txt')
def sorted_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f:
for ip in f:
if ip in ips_dict:
ips_dict[ip] += 1
else:
ips_dict[ip] = 1
sorted_ip = sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:count]
return sorted_ip
print(sorted_ip('ips.txt'))
结果:
练习3:
创建文件data.txt 文件共有100行
每行存放一个1~100之间的整数
import random
f=open('data.txt','a+')
for i in range(10):
f.write(str(random.randint(1,100))+'\n')
f.seek(0,0)
f.close()