python(file)

前言

文件操作

打开文件–>进行操作–>关闭文件

r:(默认)
只能读,不能写
读取的文件不存在,会报错
FileNotFoundError: [Errno 2] No such file or directory:
r+:
可以执行读写操作
文件不存在,报错
默认情况下,从文件指针所在位置开始写入

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

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

a:
write only
不会清空文件内容
文件不存在,会报错

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

举例

f = open('/tmp/passwd','r+')
content = f.read()
print(content)
f.write('hello')  ##插入位置在文件尾部
print(content)
print(f.readable())
print(f.writable())
f.close()

运行结果:

:0:0:root:/root:/bin/bash

:0:0:root:/root:/bin/bash

True
True
f = open('/tmp/passwd','r+')
f.write('python')   ##插入位置在文件头部
content = f.read()
print(content)
print(f.tell())
print(f.read())
print(f.tell())
f.close()

运行结果:

oot:/root:/bin/bash
hello

32

32

seek

seek方法,移动指针
seek第一个参数是偏移量:>0,代表向右移动,<0,代表向左移动
seek第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾

f = open('/tmp/passwd','rb')
print(f.tell())
print('1',f.read(3))
print(f.tell())
f.seek(-1,2)
print(f.tell())
f.seek(0)
print(f.read())
f.close()

运行结果:

0
1 b'pyt'
3
31
b'pythonoot:/root:/bin/bash\nhello\n'

复制图片文件

r r+ w w+ a a+
rb rb+ wb wb+ ab ab+

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

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

运行结果:
hello.jpg和redhat.jpg图形一样

with

f = open('/tmp/passwd')
with open('/tmp/passwd') as f:
    print(f.read())

with open('/tmp/passwd') as f1,\
    open('/tmp/passwdbackup','w+') as f2:
    f2.write(f1.read())
    f2.seek(0)
    print(f2.read())

运行结果:

pythonoot:/root:/bin/bash
hello

pythonoot:/root:/bin/bash
hello

练习

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

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

面试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(1,255)]
    # print(random.sample(ip,1))
    with open(filename,'a+') as f:
        for i in range(1200):
            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:
            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)[:count]
    return sorted_ip

print(sorted_by_ip('ips.txt'))

运行结果:

[('172.25.254.150', 12), ('172.25.254.230', 12), ('172.25.254.178', 11), ('172.25.254.235', 11), ('172.25.254.96', 10), ('172.25.254.72', 9), ('172.25.254.3', 9), ('172.25.254.237', 9), ('172.25.254.187', 9), ('172.25.254.45', 9)]

面试2

练习:
1.在当前目录新建目录img, 里面包含100个文件, 100个文件名各不>相同(X4G5.png)
2.将当前img目录所有以.png结尾的后缀名改为.jpg

import os
import string
import random

def gen_code(len=4):
    li = random.sample(string.ascii_letters + string.digits,len)
    return ''.join(li)

def creat_file():
    li = [gen_code() for i in range(100)]
    os.mkdir('img1')
    for i in li:
        os.mknod('img1/' + i + '.png')

# creat_file()
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('img1','.jpg','.png')

面试3

生成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()

后记

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章