文章目录
- 1.python中文件的管理
- 1.1读取文件
- 1 打开文件的三个步骤
- 2 查看文件的读写权限
- 3 文件读取的四个模式
- 1.2文件指针
- 1 查看文件指针所处于的位置
- 2 指针的操作(seek方法)
- 1.3 文件的读取操作
- 1 read方法
- 2 readline方法
- 3 readlines方法
- 1.4 图片的读取操作
- 1.5 文件管理中的with
- 1 with和close的区别
- 2 with同时打开2个文件
- 1.6 文件管理的练习
- 创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数
- 2.python中的OS模块
- 2.1 返回操作系统的类型
- 2.2 返回操作系统的详细信息
- 2.3 返回系统的环境变量
- 2.4 检测/生成绝对路径
- 1.判断是否为绝对路径
- 2.生成绝对路径
- 2.5 分离目录名和文件名
- 根据绝对路径获取目录名/文件名
- 分离目录名和文件名
- 2.6 删除/创建目录
- 1.创建目录
- 2.创建递归目录
- 3.删除目录
- 2.7 创建/删除文件
- 创建文件
- 删除文件
- 2.8 重命名
- 2.9 判断文件/目录是否存在
- 2.10 分离文件名和后缀名
- 3.Python中对目录的操作
- 3.1 查看目录下的路径
- 3.2 查看目录下路径中包含的目录文件
- 3.3 查看目录下路径中包含的文件
- 3.4 拼接目录和文件
- 3.5 练习
- 练习:在当前目录新建目录img, 里面包含100个文件, 100个文件名各不相同(X4G5.png); 将当前img目录所有以.png结尾的后缀名改为.jpg.
- 练习:生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
- 4.Python中对时间的管理
- 4.1 time.time()
- 4.2 获取文件的atime,ctime,mtime
- 4.3 时间之间的格式转换
- 1.把元组时间转换为时间戳
- 2.把元组时间转换为字符串
- 3.把时间戳转换为字符串
- 4.把时间戳转换为元组时间
- 4.4 练习
- 练习: 获取当前主机信息, 包含操作系统名, 主机名,内核版本, 硬件架构等;获取开机时间和开机时长;获取当前登陆用户
- 5.Python中的第三方模块
- 5.1 itchat(与微信交互)
- 1.发微信给文件助手
- 2.统计微信好友性别
1.python中文件的管理
1.1读取文件
1 打开文件的三个步骤
open -> operate -> close
注意:打开文件后一定要关闭文件,否则会占用系统资源
f = open('/etc/passwd')
content = f.read()
print(content)
f.close()
2 查看文件的读写权限
注意:默认的权限是r(只能读,不能写)
f = open('/mnt/passwd')
print(f.readable())
print(f.writable())
f.close()
3 文件读取的四个模式
r:(默认)
-只能读,不能写
-读取的文件不存在,会报错
FileNotFoundError: [Errno 2] No such file or directory
r+:
-可以执行读写操作
-文件不存在,报错
-默认情况下,从文件指针所在位置开始写入
w:
-write only
-会清空文件之前的内容
-文件不存在,不会报错,会创建新的文件并写入
w+:
-rw
-会清空文件内容
-文件不存在,不报错,会创建新的文件
a:
-write only
-不会清空文件内容
-文件不存在,会报错
a+:
-rw
-文件不存在,不报错
-不会清空文件内容
1.2文件指针
1 查看文件指针所处于的位置
注意:文件的读取从指针后读取
f = open('/mnt/passwd','r+')
print(f.tell())
f.write('python')
print(f.tell())
content = f.read()
print(content)
print(f.tell())
print(f.read())
print(f.tell())
f.close()
2 指针的操作(seek方法)
seek方法,移动指针
seek第一个参数是偏移量:>0,代表向右移动,<0,代表向左移动
seek第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾
注意: 第一个参数 受限于第二个参数
f = open('/tmp/passwd','rb')
print(f.read())
print(f.tell())
f.seek(0)
print(f.tell())
print(f.read(3))
print(f.tell())
f.seek(-1,2)
print(f.tell())
f.close()
1.3 文件的读取操作
1 read方法
read读取整个文件,将文件内容放到一个字符串变量中。
注意:如果文件非常大,尤其是大于内存时,无法使用read()方法。
f = open('/mnt/passwd','rb')
print(f.read())
f.close()
f = open('/mnt/passwd','rb')
print(f.read(4))
f.close()
2 readline方法
readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存,但比readlines慢得多
f = open('/mnt/passwd','rb')
print(f.readline())
f.close()
3 readlines方法
readlines()方法一次性读取整个文件;自动将文件内容分析成一个行的列表。
f = open('/mnt/passwd','rb')
print(f.readlines())
f.close()
1.4 图片的读取操作
对于非文件的读取方式可以通过复制操作来读取。
f1 = open('redhat.jpg',mode='rb')
content = f1.read()
f1.close()
f2 = open('copypic.jpg',mode='wb')
f2.write(content)
f2.close()
1.5 文件管理中的with
用with的方法打开文件不需要再用close关闭
with open('/tmp/passwd') as f:
print(f.read())
1 with和close的区别
2 with同时打开2个文件
在python3中
with open('/tmp/passwd') as f1,\
open('/tmp/copypasswd','w+') as f2:
f2.write(f1.read())
f2.seek(0)
print(f2.read())
在python2中
with open('/tmp/passwd') as f1:
content = f1.read()
with open('/tmp/passwd2') as f2:
f2.write(content)
print(f2.read())
在python2中要分开写
1.6 文件管理的练习
创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数
import random
f = open('date.txt','w+')
for i in range(100000):
f.write(str(random.randint(1,100))+'\n')
f.seek(0)
print(f.read())
f.close()
2.python中的OS模块
注意:需要导入os
import os
2.1 返回操作系统的类型
返回的值为posix为Linux的操作系统
返回的值为nt为Windows的操作系统
import os
print(os.name)
2.2 返回操作系统的详细信息
import os
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)
2.3 返回系统的环境变量
import os
print(os.environ)
print(os.environ.get('PATH'))
2.4 检测/生成绝对路径
1.判断是否为绝对路径
注意:不判断文件是否存在,只判断是否以/开头
import os
print(os.path.isabs('/tmp/python'))
print(os.path.isabs('python'))
2.生成绝对路径
import os
from os.path import join
print(os.path.abspath('copypic.jpg'))
print(os.path.join(os.path.abspath('.'),'copypic.jpg'))
print(os.path.join('/home/rhel8','copypic.jpg'))
2.5 分离目录名和文件名
根据绝对路径获取目录名/文件名
import os
from os.path import join
print(os.path.join('/home/rhel8','hello.jpg'))
print(os.path.basename('/home/rhel8/hello.jpg'))
print(os.path.dirname('/home/rhel8/hello.jpg'))
分离目录名和文件名
import os
from os.path import split
print(os.path.split('/tmp/file.txt'))
2.6 删除/创建目录
1.创建目录
import os
os.mkdir('filedir')
2.创建递归目录
import os
os.makedirs('dir/dir1')
3.删除目录
注意:只能删除空目录
import os
os.rmdir('filedir')
2.7 创建/删除文件
创建文件
import os
os.mknod('file.txt')
删除文件
import os
os.remove('file.txt')
2.8 重命名
import os
os.rename('date.txt','file.txt')
2.9 判断文件/目录是否存在
import os
from os.path import exists
print(os.path.exists('file.txt'))
print(os.path.exists('file1'))
2.10 分离文件名和后缀名
import os
from os.path import splitext
print(os.path.splitext('file.txt'))
3.Python中对目录的操作
3.1 查看目录下的路径
import os
for root,dir,files in os.walk('/var/log'):
print(root)
3.2 查看目录下路径中包含的目录文件
import os
for root,dir,files in os.walk('/var/log'):
print(dir)
3.3 查看目录下路径中包含的文件
import os
for root,dir,files in os.walk('/var/log'):
print(files)
3.4 拼接目录和文件
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))
3.5 练习
1. 生成一个大文件ips.txt,要求1200行, 每行随机为172.25.254.0/24段的ip;读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import random
def creat_ip_file(filename):
ip = ['172.25.254.' + str(i) for i in range(1,255)]
with open(filename,'a+') as f:
for i in range(1200):
f.write(random.sample(ip,1)[0] + '\n')
def sorted_ip_file(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)[:10]
return sorted_ip
print(sorted_ip_file('ips.txt'))
练习:在当前目录新建目录img, 里面包含100个文件, 100个文件名各不相同(X4G5.png); 将当前img目录所有以.png结尾的后缀名改为.jpg.
import random
import string
import os
def gen_code(len=4):
li = random.sample(string.ascii_letters+string.digits,len)
return ''.join(li )
def create_file():
li = [gen_code() for i in range(100)]
os.mkdir('img')
for i in li:
os.mknod('img/' + i + '.png')
def modify_suffix(dirname,old_suffix,new_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:
oldname = os.path.join(dirname,filename + old_suffix)
newname = os.path.join(dirname,filename +new_suffix)
os.rename(oldname,newname)
modify_suffix('img','.png','.jpg')
练习:生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
01-AF-3B
01-AF-3B-xx
01-AF-3B-xx-xx
01-AF-3B-xx-xx-xx
import random
import string
def create_mac():
MAC = '01-AF-3B'
hex_num = string.hexdigits
for i in range(3):
n = random.sample(hex_num,2)
sn = '-' + ''.join(n).upper()
MAC += sn
return 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()
4.Python中对时间的管理
4.1 time.time()
time.time()可以计算两个时间的间隔
4.2 获取文件的atime,ctime,mtime
import time
import os
time1 = os.path.getctime('/etc/passwd')
print(time1)
tuple_time = time.localtime(time1)
print(tuple_time)
year = tuple_time.tm_year
month = tuple_time.tm_mon
day = tuple_time.tm_mday
with open('time.txt','w') as f:
f.write('%d %d %d' %(year,month,day))
f.write('\n')
4.3 时间之间的格式转换
1.把元组时间转换为时间戳
import time
tuple_time = time.localtime()
print(tuple_time)
print(time.mktime(tuple_time))
2.把元组时间转换为字符串
import time
tuple_time = time.localtime()
print(time.strftime('%m-%d',tuple_time))
print(time.strftime('%Y-%m-%d',tuple_time))
print(time.strftime('%F',tuple_time))
print(time.strftime('%T',tuple_time))
3.把时间戳转换为字符串
import time
import os
time1 = os.path.getctime('/etc/passwd')
print(time1)
print(time.ctime(time1))
4.把时间戳转换为元组时间
import time
import os
time1 = os.path.getctime('/etc/passwd')
print(time1)
print(time.localtime(time1))
4.4 练习
练习: 获取当前主机信息, 包含操作系统名, 主机名,内核版本, 硬件架构等;获取开机时间和开机时长;获取当前登陆用户
import os
import psutil
from datetime import datetime
print('主机信息'.center(50,'*'))
info = os.uname()
print(
"""
操作系统:%s
主机名称:%s
内核版本:%s
硬件架构:%s
"""%(info.sysname,info.nodename,info.release,info.machine)
)
print('开机信息'.center(50,'*'))
boot_time = psutil.boot_time()
boot_time_obj = datetime.fromtimestamp(boot_time)
print('开机时间为:',boot_time_obj)
now_time = datetime.now()
print('当前时间为:',str(now_time).split('.')[0])
time1 = now_time - boot_time_obj
print('开机时长为:',str(time1).split('.')[0])
print('当前登陆用户'.center(50,'*'))
login_user = psutil.users()
print(login_user[0].name)
5.Python中的第三方模块
5.1 itchat(与微信交互)
1.发微信给文件助手
import itchat
import time
import random
itchat.auto_login()##登录微信
while True:
itchat.send('hello',toUserName='filehelper')
time.sleep(random.randint(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)