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