Python基础(五)

文件

文件的读取

文件读取的三部曲:打开---->操作---->关闭

# 打开文件
f = open('/tmp/passwd')

# 操作文件
# 告诉当前文件指针所在的位置
print(f.tell())

# 读操作
# content = f.read()
# print(content)

print(f.read())

# 写操作
f.write('python')

# 判断文件对象拥有的权限
print(f.readable())
print(f.writable())

# 关闭文件
f.close()

文件的操作:
r:(默认)
- read only
- 读取文件不存在,会报错
FileNotFoundError: [Errno 2] No such file or directory: ‘/tmp/passwd1’

w:
- write only
- 文件不存在,不报错,并创建新的文件
- 文件存在,会清空文件内容并写入新的内容

a:
- write only
- 文件不存在,不报错,并创建新的文件
- 文件存在,不会清空文件内容,会在文件末尾追加

r+:
- read,write
- 读:读取文件不存在,会报错
- 写:文件不存在,不报错,并创建新的文件;文件存在,默认情况下,从文件指针所在的位置开始写入

w+:
- read,write
- 读:读取文件不存在,不报错
- 写:文件不存在,不报错,并创建新的文件;文件存在,会清空文件内容并写入新的内容

a+:
- read,write
- 读:读取文件不存在,不报错
- 写:文件不存在,不报错,并创建新的文件;文件存在,不会清空文件内容,会在文件末尾追加

练习:
创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数

代码:

import random

f = open('data.txt','a+')
for i in range(100000):
    f.write(str(random.randint(1,100)) + '\n')
f.seek(0,0)
print(f.read())
f.close()

生成文件:
在这里插入图片描述

非纯文本文件的读取

读取图片,音频或视频(非纯文本文件),需要通过二进制的方式进行读取与写入
----读取文本文件
r / r+ / w / w+ / a / a+ == rt / rt+ / wt / wt+ / at / at+
----读取二进制文件
rb / rb+ / wb / wb+ / ab / ab+

# 先读取二进制文件内容
f1 = open('01.jpg',mode='rb')
content = f1.read()
f1.close()

# 写入要复制的文件读到的内容
f2 = open('02.jpg',mode='wb')
f2.write(content)
f2.close()

文件的常用操作

读操作
f = open('/tmp/passwd', 'r')
"""
默认情况下读取文件的所以内容
    小文件,直接用read()读取
    大文件(文件大小 > 内存大小),readline()
"""

# 类似于 head -c,读取前三个字节
print(f.read(3))

# 每次读取一行内容
print(f.readline())

# 读取文件内容,返回一个列表,列表元素分别为文件的行内容
print(f.readlines())

# 判断文件是否可读
print(f.readable())

f.close()

在这里插入图片描述

写操作
f = open('/tmp/passwd','w')

# 从指针所在位置写入,写的就是字符串的内容
f.write('hello')

# 将列表中的每个元素写入文件
f.writelines(['a','b'])

# 判断文件是否可写
print(f.writable())

f.close()
指针的操作
f = open('/tmp/passwd','rb')
# 告诉当前文件指针所在的位置
print(f.tell())
print('1:',f.read(3))
print(f.tell())
f.seek(0,0)
"""
seek():移动指针
    第一个参数:偏移量
        偏移量>0:代表向后移动
        偏移量<0:代表向前移动
    第一个参数:
        0:移动指针到文件开头
        1:当前位置
        2:移动指针到文件末尾
"""
print(f.tell())
f.close()

在这里插入图片描述

with

上下文管理器: 打开文件,执行完with语句内容之后,自动关闭文件对象

f = open('/tmp/passwd')
with open('/tmp/passwd') as f:
    print('with语句里面:',f.closed)
    # f.closed:文件是否关闭
    print(f.read())

print('执行完with语句后:',f.closed)

在这里插入图片描述

with_文件的复制:

# python3/python2(只能这么写)
with open('/tmp/passwd') as f1:
    content = f1.read()
with open('/tmp/passwdbackup', 'w+') as f2:
    f2.write(content)

# python3(python2不支持同时打开两个文件)
with open('/tmp/passwd') as f1, \
        open('/tmp/passwdbackup', 'w+') as f2:
    f2.write(f1.read())

练习1:
生成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

# 随机生成一个MAC地址的函数
def mac():
    MAC= '01-AF-3B'
    # 生成16进制的数
    hex_num = string.hexdigits
    for i in range(3):
        # 从16进制字符串中随机选出2个数来(返回值为列表)
        n = random.sample(hex_num,2)
        # 拼接列表中的内容,将小写字母转换为大写
        sn = '-' + ''.join(n).upper()
        MAC += sn

    return MAC

# 主函数,随机生成100个MAC地址
def main():
    # 以写的方式打开文件
    with open('mac.txt','w') as f:
        for i in range(100):
            print(mac())
            # 每生成一个MAC地址,存入文件(注意换行)
            f.write(mac+'\n')

main()

方法二:

import random
import string
   
def mac():
    MAC = '01-AF-3B'
    for i in range(3):
        # 在16进制字符串中随机生成2个字符
        n = random.choice(string.hexdigits) + random.choice(string.hexdigits)
        # 拼接列表中的内容,将小写字母转换为大写
        MAC = MAC + '-' + n.upper()
    return MAC
    
def main():
    with open('mac.txt', 'w') as f:
        for i in range(100):
            print(mac())
            f.write(str(mac()) + '\n')

main()

运行结果:
在这里插入图片描述
练习2:
生成一个大文件ips.txt,要求1200行, 每行随机为172.25.254.0/24段的ip;
读取ips.txt文件统计这个文件中ip出现频率排前10的ip;

代码:
方法一:

def ip():
    IP = '172.25.254'
    n = random.randint(0, 255)
    IP = IP + '.' + str(n)
    return IP
    
def creat_ip_file():
    with open('ips.txt', 'w') as f:
        for i in range(1200):
            f.write(str(ip()) + '\n')
    
creat_ip_file()

def sort_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(sort_ip('ips.txt'))

方法二:

def creat_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):
            f.write(random.sample(IP, 1)[0] + '\n')
    
creat_ip_file('ips.txt')
    
def sort_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(sort_ip('ips.txt'))

运行结果:
在这里插入图片描述

通过yield实现文件的读取

生成器复习:

def bylineread(fimename):
    with open(fimename) as f:
        line = f.readline()
        while line:
            yield line
            line = f.readline()

# read是一个生成器对象
read = bylineread('data.txt')
print(read)
# next读取生成器内容
print(next(read))
print(next(read))

# for循环
for item in read:
    print(item)

迭代:

from collections import Iterable

f = open('data.txt')
print(isinstance(f,Iterable))    # 结果为True,可迭代
for i,item in enumerate(f):
    if i == 10:
        break
    print(i,item)

读取文件方式速率比较

import time
import functools


def timeit(fun):
    @functools.wraps(fun)
    def add_time(*args, **kwargs):
        start_time = time.time()
        res = fun(*args, **kwargs)
        end_time = time.time()
        print('运行时间:%.6f' % (end_time - start_time))
        return res

    return add_time


@timeit
def read1(filename):
    with open(filename) as f:
        for line in f:
            # 对文件的操作处理
            line = int(line.strip())
            line = line + 1


@timeit
def read2(filename):
    with open(filename) as f:
        for line in f.readlines():
            line = int(line.strip())
            line = line + 1


read1('data.txt')
read2('data.txt')


@timeit
def copy1(sourcefile, destfile):
    with open(sourcefile) as f1:
        content = f1.read()
    with open(destfile, 'w') as f2:
        f2.write(content)


@timeit
def copy2(sourcefile, destfile):
    with open(sourcefile) as f1, open(destfile, 'w') as f2:
        f2.write(f1.read())


copy1('data.txt', 'data1.txt')
copy2('data.txt', 'data2.txt')

在这里插入图片描述

os

1.返回操作系统类型

值为posix,时Linux操作系统 值为nt,为Windows操作系统

print(os.name)
print('Linux' if os.name == 'posix' else 'Windoes')

在这里插入图片描述

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/passwd'))
print(os.path.isabs('hello'))

在这里插入图片描述

6.生成绝对路径
print(os.path.abspath('hello.png'))
print(os.path.join('/home/kiosk','hello.png'))
print(os.path.join(os.path.abspath('.'),'hello.png'))

在这里插入图片描述

7.获取目录名或文件名
filename = '/home/kiosk/PycharmProjects/2018.11.17/day09/hello.png'
print(os.path.basename(filename))
print(os.path.dirname(filename))

在这里插入图片描述

8.创建目录 删除目录
os.mkdir('img')
os.rmdir('img')
os.makedirs('img/dir')
9.创建文件 删除文件
os.mknod('file.txt')
os.remove('file.txt')
10.文件重命名
os.rename('file.txt','file1.txt')
11.判断文件或目录是否存在
print(os.path.exists('ips.txt'))
12.分离后缀名和文件名
print(os.path.splitext('hello.png'))

在这里插入图片描述

13.将目录和文件名分离
print(os.path.split('/tmp/hello/hello.png'))

在这里插入图片描述

练习1:
完成自动创建100个目录,目录名称为学生学号,学号的前四位均为‘0405’,学号总计为8位。
举例,如学号04050001

代码:

方法一:

import os

sid = 4050001

for i in range(1,101):
    res_sid = '0' + str(sid + i)
    os.mkdir(res_sid)

方法二:

import os

sid_pre = '0405'

for i in range(1,101):
    i = str(i)
    i_len = len(i)
    if i_len == 1:
        sid_last = '000' + i

    elif i_len ==2:
        sid_last = '00' + i

    elif i_len == 3:
        sid_last = '0' + i
        
    else:
        pass
        
    res_sid = sid_pre + sid_last
    os.mkdir(res_sid)

方法三:

import os

res_pre = '0405'
os.mkdir('os')

for i in range(1,101):
    res_sid = res_pre + str('%04d' %i)
    os.mkdir('os/'+res_sid)

练习2:
在当前目录新建目录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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值