1 . 文件的基本操作:
文件读取三部曲:
- 打开
- 操作
- 关闭(如果不关闭会占用文件描述符)
打开文件:
f = open('/tmp/passwdd','w')
操作文件:
1 . 读操作: f.read()content = f.read()print(content)
2 . 写操作:f.write('hello')
关闭:
f.close()
2 . 文件的读写:
r(默认参数):
-只能读,不能写
-读取文件不存在 会报错
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/westos'
r+ :
-r/w
-文件不存在,报错
-默认情况下,从文件指针所在位置开始写入w(写)
-write only
-文件不存在的时候,会自动创建新的文件
-文件存在的时候,会清空文件内容并写入新的内容
w+ :
-r/w
-文件不存在,不报错
-会清空文件内容a(追加):
-write only
-写:不会清空文件的内容,会在文件末尾追加
-写:文件不存在,不会报错,会创建新的文件并写入内容
a+ :
-r/w
-文件不存在,不报错
-不会清空文件,在末尾追加
查看文件是否可读可写:
f = open('/etc/passwd')
print(f.writable())
print(f.readable())运行结果:
False
True
如果读取是 图片 音频 视频(非纯文本文件)
需要通过二进制的方式读取和写入
-读取纯文本
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(‘lucky.jpg’,mode=‘wb’)
写入要复制的文件的内容
f2.write(content)
f2.close()
3 . 移动文件指针
seek方法,移动指针seek的第一个参数是偏移量:>0,表示向右移动,<0表示向左移动seek的第二个参数是:0:移动指针到文件开头1:不移动指针2:移动指针到末尾
f = open('file.txt','r+')
print(f.tell())
print(f.read(3))
print(f.tell())f.seek(0,1)
print(f.tell())f.close()运行结果:
0
qwd
3
3
4 . 上下文管理器
打开文件,执行完with语句内容之后,自动关闭文件。不用写close关闭文件,更方便。
f = open('/tmp/passwd')
with open('/tmp/passwd') as f:print(f.read())
#同时打开两个文件
with open('/tmp/passwd') as f1,\open('/tmp/passwd1','w+') as f2:#将第一个文件的内容写入第二个文件中f2.write(f1.read())#移动指针到文件最开始f2.seek(0)#读取文件内容print(f2.read())
练习题:
1.读取文件的内容,返回一个列表,并且去掉后面的“\n”
f = open('file.txt')
#1
print(list(map(lambda x:x.strip(),f.readlines())))
#2
print([line.strip() for line in f.readlines()])
f.close()运行结果:
['qwdeqdewfd', 'fewfwafsDfgb', 'ergeewqrwq32r53t', 'fdst542rfewg']
[]
2 . 创建文件data.txt 文件共10行,
每行存放以一个1~100之间的整数
import randomf = open('data.txt','a+')
for i in range(10):f.write(str(random.randint(1,100)) + '\n')
# 移动文件指针
f.seek(0,0)
print(f.read())
f.close()
3 . 生成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 string
import random# hex_num = string.hexdigits
# print(hex_num)
def create_mac():MAC = '01-AF-3B'# 生成16进制的数hex_num = string.hexdigitsfor i in range(3):# 从16进制字符串中随即选出两个数字来# 返回值是列表n = random.sample(hex_num, 2)# 拼接列表中的内容,将小写的字母转换成大写的字母sn = '-' + ''.join(n).upper()MAC += snreturn MAC# 主函数:随即生成100个MAC地址
def main():# 以写的方式打开一个文件with open('mac.txt', 'w') as f:for i in range(100):mac = create_mac()print(mac)# 每生成一个MAC地址,存入文件f.write(mac + '\n')main()
4 . 京东二面编程题
1 . 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
2 . 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import randomdef create_ip_file(filename):ips = ['172.25.254.' + str(i) for i in range(0,255)]print(ips)with open(filename,'a+') as f:for count in range(1200):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] += 1else:ips_dict[ip] = 1sorted_ip = sorted(ips_dict.items(),key= lambda x:x[1],reverse=True)[:count]return sorted_ip
print(sorted_ip('ips.txt',20))