1.纯文本文件的读写
打开文件的步骤:打开 --> 操作 --> 关闭
注意:文件的描述符是固定的,所以打开文件操作完成后要关闭,可用sysctl -a | grep file查看系统的文件描述符。
r:(默认)**
-只能读,不能写
-读取的文件不存在,会报错
r+:
-可读写
-文件不存在,报错
-默认从文件指针所在位置开始写入
w:
-只能写
-会清空文件之前的内容
-文件不存在,不会报错,会创建新的文件并写入
w+:
-可读写
-会清空文件内容
-文件不存在,不会报错,会创建新的文件并写入
a:
-只能写
-文件不存在,不报错
-不会清空文件内容
a+:
-可读写
-文件不存在,不报错
-不会清空文件内容
验证:
首先将/etc/passwd文件copy到/tmp/passwd
1.r(默认)
可读
f = open('/tmp/passwd','r')
content = f.read()
print(content)
f.close()
不可写:
f = open('/tmp/passwd','r')
f.write('python')
f.close()
文件不存在报错
f = open('/tmp/passwd1','r')
content = f.read()
print(content)
f.close()
2.r+
可读写,默认从指针所在位置写
f = open('/tmp/passwd','r+')
print(f.writable())
print(f.readable())
content = f.read()
f.write('python')
print(content)
print(f.tell()) #指针所在位置
f.close()
文件不存在报错
f = open('/tmp/passwd1','r+')
content = f.read()
print(content)
f.close()
3.w
只能写,会清空文件之前的内容
f = open('/tmp/passwd','w')
print(f.writable())
print(f.readable())
f.write('python')
content = f.read()
print(content)
f.close()
文件不存在,不会报错,会创建新的文件并写入
f = open('/tmp/passwd1','w')
print(f.writable())
print(f.readable())
f.write('python')
content = f.read()
print(content)
f.close()
4.w+
可读写,会清空文件内容;文件不存在,不会报错,会创建新的文件并写入
f = open('/tmp/passwd1','w+')
print(f.writable())
print(f.readable())
f.write('hello')
content = f.read()
print(content)
f.close()
5.a(追加,写到结尾)
只能写,不会清空文件内容
f = open('/tmp/passwd','a')
print(f.writable())
print(f.readable())
f.write('hello')
content = f.read()
print(content)
f.close()
文件不存在,不报错,不会清空文件内容
f = open('/tmp/passwd1','a')
print(f.writable())
print(f.readable())
f.write('hello')
content = f.read()
print(content)
f.close()
6.a+
可读写
f = open('/tmp/passwd','a+')
print(f.writable())
print(f.readable())
f.write('westos')
content = f.read()
print(content)
f.close()
文件不存在,不报错,不会清空文件内容
f = open('/tmp/passwd1','a+')
print(f.writable())
print(f.readable())
f.write('westos')
content = f.read()
print(content)
f.close()
2.文件的读取
读取/tmp/file文件,并以二进制形式输出(写在一起)
f = open('/tmp/file','rb+')
print(f.read())
f.close()
读取文件内容,返回文件中第一行的内容,并以二进制形式输出(显示第一行)
f = open('/tmp/file','rb+')
print(f.readline())
f.close()
readlines():读取文件内容,返回一个列表,列表里的元素分别为文件每行的内容
f = open('/tmp/file','rb+')
print(f.readlines())
f.close()
注意:默认情况下读取文件的所有内容,小文件可以直接用read读取,如果是大文件(文件大小>内存大小),不能通过read一次性读取所有内容
f = open('/tmp/passwd','r+')
print(f.read(4))
print(f.readline(),end='')
# print([line.strip() for line in f.readlines()])
print(list(map(lambda x:x.strip(),f.readlines())))
seek方法,移动指针
seek第一个参数是偏移量:>0,代表向右移动,<0,代表向左移动
seek第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾
f = open('/tmp/passwd','r+')
# print(f.tell()) #初始位置为开头0
# print(f.write('redhat')) #写入6个字符指针停在6位置
print(f.tell())
print(f.read())
f.seek(0,2)
print(f.tell())
print(f.read())
f.close()
非纯文本文件读取–读取二进制文件
图片、视频都是二进制文件,此时需要是要二进制文件读取方式
读取二进制文件
rb rb+ wb wb+ ab ab+
实现二进制文件的复制,在当前文件夹下复制redhat.jpg为hello.jpg
f = open('redhat.jpg',mode='rb')
content = f.read()
f.close()
f1 = open('hello.jpg',mode='wb')
f1.write(content)
f1.close()
4.上下文管理器
使用上下文管理器可以不使用open和close
with open('/tmp/passwd') as f:
print(f.read())
举例说明如何将/tmp/passwd中的内容移动至新的文件中
with open('/tmp/passwd') as f1,\
open('/tmp/passwd1','w+') as f2:
f2.write(f1.read())
f2.seek(0,0)
print(f2.read())
练习:
创建文件data.txt,共100000行,每行存放一个1~100之间的整数
import random
f = open('data.txt','w+')
for i in range(100000):
f.write(str(random.randint(1,100)) + '\n')
f.seek(0,0)
print(f.read())
f.close()
练习:
- 在当前目录新建目录img, 里面包含100个文件, 100个文件名
各不相同(X4G5.png) - 将当前img目录所有以.png结尾的后缀名改为.jpg.
import random
import string
import os
from os.path import splitext
def gen_code(len=4):
#随机生成4位验证码
li = random.sample(string.ascii_letters+string.digits,len)
#拼接为字符串
return ''.join(li)
def create_files():
#随机生成100个验证码
li = [gen_code() for i in range(100)]
os.mkdir('img')
for i in li:
os.mknod('img/' + i + '.png')
create_files()
def modify_suffix(dirname,old_suffix,new_suffix):
#找出以png结尾的文件名
# pngfile = [filename for filename in os.listdir(dirname) if filename.endswith(old_suffix)]
pngfile = filter(lambda filename:filename.endswith(old_suffix),os.listdir(dirname))
#分离文件名和后缀
basefiles = [os.path.splitext(filename)[0] for filename in pngfile]
#文件重命名
for filename in basefiles:
# print(filename)
oldname = os.path.join(dirname,filename + old_suffix)
newname = os.path.join(dirname,filename + new_suffix)
os.rename(oldname,newname)
print('%s重命名为%s成功' %(oldname,newname))
modify_suffix('img','.png','.jpg')
2.京东二面笔试题
- 生成一个大文件ips.txt,要求1200行
每行随机为172.25.254.0/24段的ip; - 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import random
def create_ip(filename):
ip = ['172.25.254.' + str(i) for i in range(1,255)]
# print(random.sample(ip,1))
with open(filename,'a+') as f:
for i in range(1200):
f.write(random.sample(ip,1)[0] + '\n')
create_ip('ips.txt')
def sorted_by_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f:
for ip in f:
ip = ip.strip()
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_by_ip('ips.txt'))