python中的文件管理、时间管理与第三方模块

文章目录

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)

在这里插入图片描述

在这里插入图片描述

如果你是一个小型的办公网络,你可以创建一个服务器来进行日程安排,这只是一个开源的小服务器,你果你需要大的免费的软件去http://www.bedework.org/bedework/下载 使用教程 Installation Dependencies Radicale is written in pure python and does not depend on any librabry. It is known to work on Python 2.5, 2.6, 3.0 and 3.1 [1]. Linux users certainly have Python already installed. For Windows and MacOS users, please install Python [2] thanks to the adequate installer. [1] See Python Versions and OS Support for further information. [2] Python download page. Radicale Radicale can be freely downloaded on the project website, download section. Just get the file and unzip it in a folder of your choice. CalDAV Clients At this time Radicale has been tested and works fine with the latests version of Mozilla Sunbird (versions 0.9+), Mozilla Lightning (0.9+), and Evolution (2.30+). More clients will be supported in the future. However, it may work with any calendar client which implements CalDAV specifications too (luck is highly recommanded). To download Sunbird, go to the Sunbird project website and choose the latest version. Follow the instructions depending on your operating system. Simple Usage Starting Server To start Radicale CalDAV server, you have to launch the file called radicale.py located in the root folder of the software package. Using Sunbird or Lightning After starting Sunbird or Lightning, click on File and New Calendar. Upcoming window asks you about your calendar storage. Chose a calendar On the Network, otherwise Sunbird will use its own file system storage instead of Radicale's one and your calendar won't be remotely accessible. Next window asks you to provide information about remote calendar access. Protocol used by Radicale is CalDAV. A standard location for a basic use of a Radicale calendar is http://localhost:5232/user/calendar/, where you can replace user and calendar by some strings of your choice. Calendars are automatically created if needed. You can now customize your calendar by giving it a nickname and a color. This
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值