python------文件

本文详细介绍Python中文件的打开、读写、关闭等基本操作,包括不同模式下的操作特点,以及如何处理非纯文本文件。同时,文章还介绍了如何使用Python进行基本的系统操作,如读取系统信息、环境变量,创建、删除文件和目录,以及遍历目录等。最后,通过一个生成MAC地址并写入文件的实例,加深理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、文件

“”"
打开文件的三个步骤:打开—>操作—>关闭
“”"

# f = open('/tmp/pass','a')
# content = f.read()
# print(content)
# f.write('hello')
# print(f.readable())
# print(f.writable())
# f.close()

“”"
r:(默认)
-只能读,不能写
-读取文件不存在,会报错

r+:
-可读写
-读取文件不存在,会报错

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

w+:
-rw
-会清空文件内容
-文件不存在,不报错,会创建新的文件

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

a+:
-rw
-文件不存在不报错
-不会清空文件内容

“”"

f = open('/tmp/passwd','r+')
content = f.read()
print(content)
print(f.tell())
f.write('python')
print(f.tell())
print(f.read())
print(f.tell())
f.close()

二、文件的读取操作

f = open('/tmp/passwd','rb')
# print(f.read())
# print(f.readline())
# print(f.readlines())
#readlines():读取文件内容,返回一个列表,列表的元素分别为文件行的那内容

#类似于head -c 4 /tmp/passwd
# print(f.read(4))
# print([line.strip() for line in f.readlines()])
# print(list(map(lambda x:x.strip(),f.readlines())))
#告诉当前指针所在位置
print(f.tell())
print(f.read(3))
print(f.tell())
"""
seek方法,移动指针
    seek第一个参数是偏移量:>0,代表向右移动,<0,代表向左移动
    seek第二个参数是:
        0:移动指针到文件开头
        1:不移动指针
        2:移动指针到末尾
"""
f.seek(-1,2)
print(f.tell())

f.close()

三、非纯文本文件的读取

f1 = open('1111.jpg',mode='rb')
content = f1.read()
f1.close()

f2 = open('westos.jpg',mode='wb')
f2.write(content)
f2.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())

五、操作系统

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/PycharmProjects/westos_python/day08/hello.png'
#获取路径中的文件名
# print(os.path.basename(filename))
#获取路径中的目录名
# print(os.path.dirname(filename))

#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')

#11.判断文件或者目录是否存在
# print(os.path.exists('data.txt'))

#12.分离后缀名和文件名
# print(os.path.splitext('data.txt'))

#13.将目录名和文件名分离
# print(os.path.split('/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))

七、练习

"""
生成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

#随机生成一个mac地址
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

# print(create_mac())

#随机生成100个MAC 地址
def main():
    with open('mac.txt','w') as f:
        for i in range(100):
            mac = create_mac()
            print(mac)
            #每生成一个MAC地址,存入文件
            f.write(mac + '\n')

main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值