前言
文件操作
打開文件–>進行操作–>關閉文件
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()