Python 编程——文件操作

一、文件操作

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

实验操作前事先将/etc/passwd拷贝到/tmp下,方便实验效果展示

r模式(默认)

      只能读,不能写
          -读取文件不存在,会报错

f = open('/tmp/passwd')
print(f)
content = f.read()
print(content)
f.close()

Python 编程——文件操作
文件不存在时:
Python 编程——文件操作

w模式

      只能写
          -文件不存在,不报错,并创建新的文件写入内容
          -文件存在,会清空文件内容并写入新的内容

f = open('/tmp/passwd','w')
print(f)
f.write('hello')
f.close()

Python 编程——文件操作
文件不存在时:
Python 编程——文件操作

a模式

      只能写
          -文件不存在,不报错,并创建新的文件写入内容
          -文件存在,不会清空原文件的内容,会在文件末尾追加

f = open('/tmp/passwd','a')
print(f)
f.write('python')
f.close()

Python 编程——文件操作
文件不存在时:
Python 编程——文件操作

r+模式

      读写
          -文件不存在,报错
          -文件存在,默认情况下,从文件指针所在位置开始写入

f = open('/tmp/passwd','r+')
print(f)
content = f.read()
print(content)
#告诉当前文件指针所在的位置
print(f.tell())
f.write('linux')
f.close()

Python 编程——文件操作
Python 编程——文件操作
文件不存在时:
Python 编程——文件操作

w+模式

      读写
          -文件不存在,不报错
          -读的时候文件存在,读完会清空文件内容;写的时候,也会清空内容再进行写入
文件存在时,进行读:
Python 编程——文件操作
文件存在时进行写入,写之前文件内容是linux:
Python 编程——文件操作

a+模式

      读写
          -文件不存在,不报错
          -不会清空文件内容,在末尾追加

文件存在时进行读:
Python 编程——文件操作
文件存在时进行写入:
Python 编程——文件操作

判断文件对象所拥有的权限
f = open('/tmp/passwd','a+')
print(f)
#判断文件是否拥有读的权限
print(f.readable())
#判断文件是否拥有写的权限
print(f.writable())
f.close()

Python 编程——文件操作

二、非纯文本文件的操作

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

简单示例:
将照片进行复制;

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

f2 = open('python.jpg',mode='wb')
f2.write(content)
f2.close()

Python 编程——文件操作

二、文件的常用操作方法

默认情况下会读取文件所有内容,小的文件,直接用read进行读取
如果是一个大文件(文件大小>内存大小) 直接用readline()读取(一行一行读取,但后面会有空行)
区别:
read():读取文件内容,在一行输出

f = open('/tmp/passwd','r')
print(f.read())
f.close()

Python 编程——文件操作
readline():读取文件内容,输出第一行

f = open('/tmp/passwd','r')
print(f.readline())
print(f.readline())		#输出两行
f.close()

Python 编程——文件操作
readlines():读取文件内容,返回一个列表,列表的元素分别为每行的内容

f = open('/tmp/passwd','r')
print(f.readlines())
f.close()

Python 编程——文件操作
去掉列表里的\n:
方法一:

f = open('/tmp/passwd')
print([line.strip() for line in f.readlines()])
f.close()

方法二:

f = open('/tmp/passwd')
print(list(map(lambda x:x.strip(),f.readlines())))
f.close()

1.按字符读取文件内容

f = open('/tmp/passwd','r')
#读取前三个字符
print(f.read(3))
#显示当前指针所在位置
print(f.tell())
f.close()

Python 编程——文件操作

2.seek:指针移动

第一个参数:
偏移量>0:代表向后移动 <0:代表向前移动

第二个参数:
0:移动指针到文件开头
1:当前位置
2:移动指针到文件末尾
f.seek(0,0)指针归0
f.seek(-1,2)指针执行末尾,再向左移动一个字符

f = open('/tmp/passwd','rb')
print(f.tell())		#指针刚开始在0
print(f.read(3))
print(f.tell())		#读取三个字符后,指针位置在3
f.seek(0,0)		#让指针归0
print(f.tell())		#此时指针位置在0
f.close()

Python 编程——文件操作
练习题:
创建文件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')
#让指针归0,因为写完内容指针在末尾,打印的话看不到内容
f.seek(0,0)
print(f.read())
f.close()

3.with 上下文管理器

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

f = open('/tmp/passwd')
with open('/tmp/passwd') as f:
    print('with语句里面:',f.close())
    print(f.close())

print('after with语句后:',f.closed)		#查看文件是否已经关闭

Python 编程——文件操作
python3.x系列里:将一个文件内容写入另一个文件里

with open('data.txt') as f1,open('data1.txt','w+') as f2:
    # 将第一个文件的内容写入第二个文件中
    f2.write(f1.read())
    f2.seek(0,0)
    print(f2.read())

python2.x系列里:将一个文件内容写入另一个文件里

with open('data.txt')as f1:
    content=f1.read()
with open('data2.txt','w+') as f2:
    f2.write(content)
    f2.seek(0,0)
    print(f2.read())

练习题:
生成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
def create_mac():
    MAC = '01-AF-3B'
    #生成16进制的数
    hex_num = string.hexdigits
    for i in range(3):
        #从16进制字符串中随机选择两位来(返回值是列表)
        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):
            mac = create_mac()
            print(mac)
            #每生成一个MAC地址,存入文件
            f.write(mac + '\n')

main()

京东二面编程题
1.生成一个大文件ips.txt,要求1200行, 每行随机为172.25.254.0/24段的ip;
2.读取ips.txt文件统计这个文件中ip出现频率排前10的ip;

import random
def create_ip_file(filename):
    ips = ['172.25.254.' + str(i) for i in range(0,255)]
    #print(ips)
    with open(filename,'a+') as f:
        for count in range(1200):
            f.write(random.sample(ips,1)[0] + '\n')
            #random.sample(ips,1)==['172.25.254.x']
create_ip_file('ips.txt')
def sorted_ip(filename,count=10):
    ips_dict = dict()
    with open(filename) as f:
        f = [line.strip() for line in f.readlines()]
        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_ip('ips.txt'))