文件管理
1.文件操作3步曲:打开–>操作—>关闭
r(readonly)默认参数
-只能读,不能写
-读取文件不存在 会报错
w
-写文件
-文件存在的时候,会清空文件的内容并写入新的文件内容
-文件不存在的时候,会创建新的文件并写入内容a
-写文件(write only)
-写:不会清空文件内容,会在文件末尾追加
-写:文件不存在的时候,不会报错,会创建新文件并写入内容w+
-r/w
-文件不存在 不报错 会创建新文件并写入
-会清空文件
r+
-r/w
-不会清空文件
-文件不存在 报错
a+
# 1.打开文件
f = open('/tmp/passwd','r')
# 2.操作
print(f)
# 写文件
print(f.read())
f.write('python')
# 读文件
# 判断文件对象拥有的权限
print(f.readable())
print(f.writable())
print(f.tell())
print(f.read())
# 告诉当前文件指针所在的位置
print(f.tell())
print(f.read())
print(f.tell())
# 输入
f.write('westos')
# 3.关闭
f.close()
2.如果读取的是 图片 音频 视频(非纯文本文件),需要通过二进制的方式读取和写入
-读取纯文本文件
r r+ w w+ a a+ == rt rt+ wt wt+ at at+
-读取二进制文件
# 读取二进制文件内容
f1 = open('hello.jpg',mode='rb')
content = f1.read()
f1.close()
f2 = open('lucky.jpg',mode='wb')
# 写入要复制的文件的内容
f2.write(content)
f2.close()
3.read和readline
f = open('/tmp/passwd','rb+')
默认情况下读取文件的内容 小的文件:直接用read读取即可
如果是一个大文件(文件大小>=内存) readline()
# # 按行读取
print(f.readline()) #\n
print(f.readline())
# 按字节读取
print(f.read(3))
print(f.tell())
# 读取文件内容 并返回一个列表 列表元素分别为文件的行内容
# 读取内容,返回一个列表 去掉后面的\n
print(f.readlines())
# #指针的移动
print(f.read(3))
print(f.tell())
"""
seek():指针的移动
第一个参数:偏移量 >0:向后移动 <0:向前移动
第二个参数:
0:移动到文件开头
1:当前位置
2:移动到文件的末尾
"""
f.seek(1,0)
print(f.tell())
f.close()
# 创建文件data.txt 文件共有100000行
# 每行存放一个1~100之间的整数
import random
f = open('data.txt','a+')
for i in range(100000):
f.write(str(random.randint(1,100)) + '\n')
f.seek(0,0)
print(f.read())
f.close()
f = open('/tmp/passwd')
print(list(map(lambda x:x.strip(),f.readlines())))
print([line.strip() for line in f.readlines()])
f.close()
4.上下文管理器:打开文件 执行完with语句后 自动关闭文件
f = open('/tmp/passwd')
# 将第一个文件的内容写入第二个文件中
with open('data.txt') as f,open('data2.txt','w+') as f2:
f2.write(f.read())
f2.seek(0,0)
print(f2.read())
# python2.x
# """
# with open('data.txt') as f:
# content = f.read()
# with open('data2.txt') as f2:
# f2.write(content)
# """
5.练习
生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
01-AF-3B-xx-xx-xx
-xx
01-AF-3B-xx
-xx
01-AF-3B-xx-xx
-xx
01-AF-3B-xx-xx-xx
import random
import string
# print(string.hexdigits)
def create_mac():
mac = '01-AF-3B'
# 生成16进制的数
hex_num = string.hexdigits
for i in range(3):
# 从16进制字符串中随机选择两个数字
# 返回值是一个列表
n = random.sample(hex_num,2)
# 拼接列表的内容 将小写的字母转换成大写的字母
sn = '-' + ''.join(n).upper()
mac += sn
return mac
# 主函数 随机生成100 mac地址
def main():
with open('mac.txt','w') as f:
for i in range(100):
mac = create_mac()
print(mac)
f.write(mac + '\n')
main()