1 . 文件的基本操作:
文件讀取三部曲:
- 打開
- 操作
- 關閉(如果不關閉會占用文件描述符)
打開文件:
f = open('/tmp/passwdd','w')
操作文件:
1 . 讀操作: f.read()content = f.read()print(content)
2 . 寫操作:f.write('hello')
關閉:
f.close()
2 . 文件的讀寫:
r(默認參數):
-只能讀,不能寫
-讀取文件不存在 會報錯
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/westos'
r+ :
-r/w
-文件不存在,報錯
-默認情況下,從文件指針所在位置開始寫入w(寫)
-write only
-文件不存在的時候,會自動創建新的文件
-文件存在的時候,會清空文件內容并寫入新的內容
w+ :
-r/w
-文件不存在,不報錯
-會清空文件內容a(追加):
-write only
-寫:不會清空文件的內容,會在文件末尾追加
-寫:文件不存在,不會報錯,會創建新的文件并寫入內容
a+ :
-r/w
-文件不存在,不報錯
-不會清空文件,在末尾追加
查看文件是否可讀可寫:
f = open('/etc/passwd')
print(f.writable())
print(f.readable())運行結果:
False
True
如果讀取是 圖片 音頻 視頻(非純文本文件)
需要通過二進制的方式讀取和寫入
-讀取純文本
r r+ w w+ a a+ == rt rt+ wt wt+ at at+
-讀取二進制文件
rb rb+ wb wb+ ab ab+
先讀取二進制文件內容
f1 = open(‘hello.jpg’,mode=‘rb’)
content = f1.read()
f1.close()
f2 = open(‘lucky.jpg’,mode=‘wb’)
寫入要復制的文件的內容
f2.write(content)
f2.close()
3 . 移動文件指針
seek方法,移動指針seek的第一個參數是偏移量:>0,表示向右移動,<0表示向左移動seek的第二個參數是:0:移動指針到文件開頭1:不移動指針2:移動指針到末尾
f = open('file.txt','r+')
print(f.tell())
print(f.read(3))
print(f.tell())f.seek(0,1)
print(f.tell())f.close()運行結果:
0
qwd
3
3
4 . 上下文管理器
打開文件,執行完with語句內容之后,自動關閉文件。不用寫close關閉文件,更方便。
f = open('/tmp/passwd')
with open('/tmp/passwd') as f:print(f.read())
#同時打開兩個文件
with open('/tmp/passwd') as f1,\open('/tmp/passwd1','w+') as f2:#將第一個文件的內容寫入第二個文件中f2.write(f1.read())#移動指針到文件最開始f2.seek(0)#讀取文件內容print(f2.read())
練習題:
1.讀取文件的內容,返回一個列表,并且去掉后面的“\n”
f = open('file.txt')
#1
print(list(map(lambda x:x.strip(),f.readlines())))
#2
print([line.strip() for line in f.readlines()])
f.close()運行結果:
['qwdeqdewfd', 'fewfwafsDfgb', 'ergeewqrwq32r53t', 'fdst542rfewg']
[]
2 . 創建文件data.txt 文件共10行,
每行存放以一個1~100之間的整數
import randomf = open('data.txt','a+')
for i in range(10):f.write(str(random.randint(1,100)) + '\n')
# 移動文件指針
f.seek(0,0)
print(f.read())
f.close()
3 . 生成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# hex_num = string.hexdigits
# print(hex_num)
def create_mac():MAC = '01-AF-3B'# 生成16進制的數hex_num = string.hexdigitsfor i in range(3):# 從16進制字符串中隨即選出兩個數字來# 返回值是列表n = random.sample(hex_num, 2)# 拼接列表中的內容,將小寫的字母轉換成大寫的字母sn = '-' + ''.join(n).upper()MAC += snreturn 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()
4 . 京東二面編程題
1 . 生成一個大文件ips.txt,要求1200行,每行隨機為172.25.254.0/24段的ip;
2 . 讀取ips.txt文件統計這個文件中ip出現頻率排前10的ip;
import randomdef 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')create_ip_file('ips.txt')def sorted_ip(filename,count=10):ips_dict = dict()with open(filename) as f:for ip in f:if ip in ips_dict:ips_dict[ip] += 1else:ips_dict[ip] = 1sorted_ip = sorted(ips_dict.items(),key= lambda x:x[1],reverse=True)[:count]return sorted_ip
print(sorted_ip('ips.txt',20))