一、文件
- 打开文件的三个步骤:打开————>操作————>关闭
- 用/mnt/hui这个文件做实验,给文件777权限便于看到实验效果
[root@foundation2 mnt]# chmod 777 hui
[root@foundation2 mnt]# cat hui
good girl
r(默认):
- 只能读不能写
- 读曲文件不存在则,会报错
f = open('/mnt/hui') ##打开文件,后面不加东西,默认为r
content = f.read() print(content) ##打印读出的文件内容
print(f.readable()) ##打印是否可读
print(f.writable()) ##打印是否可写
f.close() ##打开文件,操作过后一定要记得关闭文件,否则会占用系统资源
结果:
good girl
True
False
r+:
- 可读写
- 读取文件不存在,会报错
- 如果在此模式下写入东西,则会从文件的第一个字母开始替换(默认情况下,从文件指针所指位置开始写入)
f = open('/mnt/hui','r+')
f.write('hui')
print(f.readable())
print(f.writable())
f.close()
结果:
rue
True
文件内容会变成:huid girl (原来是:good girl)
w:
- 只写
- 会清空原文件的内容
- 如果文件不存在,不会报错,会创建新的文件并写入
f = open('/mnt/hui','w')
f.write('hello')
print(f.readable())
print(f.writable())
f.close()
结果:
False ##不可读
True
此时文件内容为:hello
w+:
- 可读写
- 会清空文件内容
- 文件不存在,不会报错,会创建新文件并写入
f = open('/mnt/hui','w+')
f.write('world')
print(f.readable())
print(f.writable())
f.close()
结果:
True
True
此时文件内容为:world
a:
- 只写
- 不覆盖原文件内容
- 如果文件不存在,不会报错,会创建新的文件并写入
f = open('/mnt/hui','a')
f.write('westos')
print(f.readable())
print(f.writable())
f.close()
结果:
False
True
此时文件内容为:
worldwestos ##不覆盖原文件内容在后面追加
a+:
- 可读写
- 不会清空文件内容,写的内容会在换行追加
- 文件不存在,不会报错,会创建新的文件并写入
f = open('/mnt/hui','a+')
f.write('hello')
print(f.readable())
print(f.writable())
f.close()
结果:
True
True
此时文件内容为:
worldwestos
hello
```
二、文件的读取操作
文件的指针:
f = open('/mnt/hui','r+')
content = f.read()
print(content)
print(f.tell())
f.write('python')
print(f.tell())
print(f.read())
print(f.tell())
f.close()
结果:
hello ##读取文件内容
6 ##读取完成,指针默认到字符后
12 ##添加'python'后的文件指针+6,变成12
##再次读取文件时就为空了,因为:指针所在位置为文件内容的最后
12 ##指针仍为12
- 区分:
- .read()
- .readline()
- .redalines()
f = open('/mnt/passwd','rb')
print(f.read())f = open('/mnt/passwd','rb')
print(f.read()) ##读取文件内容,在一行输出
f.close()
f = open('/mnt/passwd','rb')
print(f.readline()) ##读取文件内容,输出第一行
f.close()
结果:
b'root:x:0:0:root:/root:/bin/bash\n'
f = open('/mnt/passwd','rb')
print(f.readline())
print(f.readline()) ##读取两行内容,则需要写两边readline
f.close()
结果:
b'root:x:0:0:root:/root:/bin/bash\n'
b'bin:x:1:1:bin:/bin:/sbin/nologin\n'
f = open('/mnt/passwd','rb')
print(f.readlines()) ##读取文件内容,返回一个列表,列表的元素分别为文件的每行内容
f.close()
- 取出文件的前4个字符(类似于head -c 4 /mnt/passwd)
f = open('/mnt/passwd','rb')
print(f.read(4))
f.close()
结果:
b'root'
- 去掉文件每行的空格(\n也属于空格)
f = open('/mnt/passwd','rb')
print([line.strip()for line in f.readlines()])
f.close()
##也可以用匿名函数写
print(list(map(lambda x:x.strip(),f.readlines())))
- seek方法,移动指针
- seek第一个参数是偏移量:>0,代表向右移动;<0,代表向左移动
- seek第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾
f.seek(0,0) 指针回0
f.seek(-1,2) 指针指向末尾,再向左移动一个位置
f = open('/mnt/passwd','rb')
print(f.tell()) ##指针一开始在0的位置
print(f.read(3)) ##读取三个字母
print(f.tell()) ##指针变为3
f.seek(0,0) ##指针回0
print(f.tell()) ##打印指针已经变为0
f.close()
结果:
0
b'roo'
3
0
- 练习题:
- 创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数
import random
f = open('date.txt','a+')
for i in range(100000):
f.write(str(random.randint(1,100)) + '\n')
f.seek(0,0)
print(f.read())
f.close()
文件——with
- 上下文管理器:打开文件,执行完with语句内容之后,自动关闭文件对象
#同时打开两个文件对象
with open('/tmp/passwd') as f1,open('/tmp/passwdbackup','w+') as f2:
#将第一个文件的内容写入到第二个文件中
f2.write(f1.read())
#移动指针到文件最开始
f2.seek(0)
#读取文件内容
print(f2.read())
三、操作系统(os)
import os
from os.path import exists,splitext,join
1.返回操作系统类型
值为:posix,是linux系统,如果是nt,是windows系统
print(os.name)
2.操作系统的详细信息
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)
3.系统环境变量
print(os.environ)
4.通过key值获取环境变量对应的value值
print(os.environ.get('PATH'))
5.判断是否为绝对路径
print(os.path.isabs('/tmp/hello')) ##带/的是绝对路径,否则不是
print(os.path.isabs('hello'))
6.生成绝对路径
print(os.path.abspath('hello.png'))
print(os.path.join('/home/kiosk','hello.png'))
7.获取目录名或文件名
filename = '/home/kiosk/day08/hello.png'
##获取路径中的文件名
print(os.path.basename(filename)) ##文件名为:hello.png
##获取路径中的目录名
print(os.path.dirname(filename)) ##目录名为:/home/kiosk/day08
8.创建目录/删除目录
os.mkdir('img')
os.makedirs('img/file') #创建递归目录
os.rmdir('img')
9.创建文件/删除文件
os.mknod('westos.txt')
os.remove('westos.txt')
10.文件重命名
os.rename('westos.txt','data.txt') ##重命名为date
11.判断文件或者目录是否存在
print(os.path.exists('data.txt'))
12.分离后缀名和文件名
print(os.path.splitext('data.txt'))
('data', '.txt')
13.将目录名和文件名分离
print(os.path.split('/tmp/hello/hello.png'))
('/tmp/hello', 'hello.png')
遍历目录的方法:
import os
from os.path import join
for root,dir,files in os.walk('/var/log'):
# print(root)
# print(dir)
# print(files)
for name in files:
print(join(root,name))
京东二面笔试题
- 生成一个大文件ips.txt,要求1200行,
每行随机为172.25.254.0/24段的ip; - 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import random
def create_ip_file(filename):
ip = ['172.25.254.' + str(i) for i in range(0,255)]
with open(filename,'a+') as f:
for count in range(1200):
# print(random.sample(ip,1)) ##random.sample返回的是列表
f.write(random.sample(ip,1)[0] + '\n')
create_ip_file('ips.txt') ##调用函数,生成1200行
def sorted_by_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_by_ip('ips.txt'))
四、非纯文本文件的读取
- 读取图片,音频或视频(非纯文本文件),需要以二进制的方式读取或写入
- 将一张图片放到当前路径下
扫描二维码关注公众号,回复:
5248847 查看本文章
并在当前路径下执行以下的代码
##读二进制文件内容
f1 = open('1111.jpg',mode='rb')
content = f1.read()
f1.close()
##将内容写入到新的文件中
f2 = open('westos.jpg',mode='wb')
f2.write(content)
f2.close()
可以看到生成了新的文件westos,就是刚才的图片
五、python - 文件练习题:生成100个MAC地址写入文件
题目要求:
- 生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
import string
import random
# 随机生成一个MAC地址的函数
def creat_mac():
MAC= '01-AF-3B'
# 生成16进制的数
hex_num = string.hexdigits
# 0123456789abcdefABCDEF
for i in range(3):
# 从16进制字符串中随机选出2个数来(返回值为列表)['a', 'd']
n = random.sample(hex_num,2)
# 拼接列表中的内容,将小写字母转换为大写-AD
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= creat_mac()
print(mac)
# 每生成一个MAC地址,存入文件(注意换行)
f.write(mac+'\n')
main()
结果:
01-AF-3B-E5-9B-15
01-AF-3B-C8-39-74
01-AF-3B-CA-86-CA
01-AF-3B-6C-10-C0
01-AF-3B-2D-12-63
01-AF-3B-EA-3E-EF
01-AF-3B-1B-1C-E9
01-AF-3B-FD-CC-DB
01-AF-3B-FE-95-49
01-AF-3B-95-EA-9E
01-AF-3B-DA-75-AD
01-AF-3B-8A-A1-F7
01-AF-3B-BD-75-7D
01-AF-3B-42-B6-B9
01-AF-3B-5D-A2-F6
六、python——操作系统相关练习题
- 题目要求:
- 在当前目录新建目录img, 里面包含多个文件, 文件名各不相同(X4G5.png)
- 将当前img目录所有以.png结尾的后缀名改为.jpg
import os
import string
import random
def gen_code(len=4):
# 随机生成4位的验证码
li = random.sample(string.ascii_letters + string.digits, len)
return ''.join(li)
def create_file():
# 随机生成100个验证码
li = {gen_code() for i in range(100)}
os.mkdir('img')
for name in li:
os.mknod('img/' + name + '.png')
# create_file()
def modify_suffix(dirname, old_suffix, new_suffix):
"""
:param dirname:操作的目录
:param old_suffix: 之前的后缀名
:param new_suffix: 新的后缀名
:return:
"""
# 1.判断查找的目录是否存在,如果不存在,报错
if os.path.exists(dirname):
# 2.找出所有以old_suffix(.png)结尾的文件
pngfile = [filename for filename in os.listdir(dirname) if filename.endswith(old_suffix)]
# 或者用以下的方式
# pngfiles = filter(lambda filename:filename.endswith(old_suffix),os.listdir(dirname))
# 3.将文件名和后缀名分开,留下文件名
basefiles = [os.path.splitext(filename)[0] for filename in pngfile]
print(basefiles)
# 4.文件重命名
for filename in basefiles:
#需要加上目录名
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))
else:
print('%s不存在,不能操作....' %(dirname))
modify_suffix('img','.jpg','.png')
七、python——第三方模块(itchat)
练习1: 给微信手机助手发送消息(hello)
import itchat
import time
import random
itchat.auto_login()
while True:
itchat.send('hello',toUserName='filehelper')
time.sleep(random.randint(1,3)) ##随机隔1~3秒
练习2: 统计微信好友男性,女性和其他的数量
import itchat
import time
import random
itchat.auto_login()
friends = itchat.get_friends()
info = {}
for friend in friends[1:]:
if friend['Sex'] == 1:
info['male'] = info.get('male',0) +1
elif friend['Sex'] == 2:
info['female'] =info.get('female',0) +1
else:
info['other'] = info.get('other',0) +1
print(info)
- 练习3:
需求:给文件助手发送消息,执行发送的内容
1.如果执行成功,显示执行结果
2.如果执行失败,显示执行失败
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
if msg['ToUserName'] == 'filehelper':
#获取要执行命令的内容
command = msg['Content']
print(command)
#让电脑执行命令代码
#如果执行成功,返回值为0
if os.system(command) == 0:
res = os.popen(command).read()
result = '【返回值】 - 命令执行成功,执行结果:\n' + res
itchat.send(result,'filehelper')
#命令执行失败,请重新输入命令
else:
result = '【返回值】 - 命令%s执行失败,请重试' %command
itchat.send(result,'filehelper')
itchat.auto_login()
itchat.run()