Python—文件管理

一.文件的操作步骤

"""
打开文件的三个步骤:打开--->操作--->关闭
"""
# 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 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))

七.文件练习

1.练习1

"""
# 京东二面笔试题
# 1. 生成一个大文件ips.txt,要求1200行,
     每行随机为172.25.254.0/24段的ip;
# 2. 读取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))
            f.write(random.sample(ip,1)[0] + '\n')

create_ip_file('ips.txt')

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

2.练习2

"""
# _*_coding:utf-8_*_
Name:day09.py
Date:1/22/19
Author:westos-dz
"""
"""
# #   1. 在当前目录新建目录img, 里面包含100个文件, 100个文件名
各不相同(X4G5.png)
# #   2. 将当前img目录所有以.png结尾的后缀名改为.jpg.
"""

3.操作系统练习1

"""
# _*_coding:utf-8_*_
Name:01_练习.py
Date:1/23/19
Author:westos-dz
"""
"""
生成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
# print(string.hexdigits)

def gen_code(len =2 ):
    num = random.sample(string.hexdigits,len)    ##string.hexdigits生成一行16进制字符
    return ''.join(num)

f = open('/tmp/test1','w+')   ##生成一个文件
for i in range(100):          ##行循环
    f.write('01-AF-3B')
    for j in range(i) :       ##列循环
        random_str1 = gen_code()
        f.write('-' + random_str1)
    f.write('\n')             ##每一行的列循环结束,换行

f.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值