一.文件操作三部曲:
1.打開:
f = open('文件名')
文件名后不加任何時,默認是r以只讀的方法打開
r:只能讀,不能寫。讀取文件不存在時會報錯
r+:可讀,可寫。讀取文件不存在時會報錯
w:只能寫,不能讀。文件存在時,會清空文件覆蓋文件內(nèi)容;文件不存在時,會新建文件。
w+:可寫,可讀。文件存在時,會清空文件覆蓋文件內(nèi)容;文件不存在時,會新建文件。
a:只能寫,不能讀。文件存在時,不會清空文件內(nèi)容;文件不存在時,新建文件不報錯。
a+:可寫,可讀。文件存在時,不會清空文件內(nèi)容;文件不存在時,新建文件不報錯。
2.操作:
讀:content = f.read()
##read()讀取整個文件
##readline()只讀取一行
print content
寫:f.write('寫入內(nèi)容')
3.關(guān)閉:
f.close()
vcmV2ZXJfeWg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70″ />
二.文件指針:
文件指針標記從哪個位置開始讀取數(shù)據(jù)
第一次打開文件時,通常文件指針會指向文件的開始位置,當執(zhí)行了read方法后,文件指針會移動到讀取內(nèi)容的末尾(文件指針指到了文件的最后一行,就讀取不到文件的內(nèi)容)。
三.讀取大型文件時:
因為不知道循環(huán)的條件,不知道文件到底有多少行,所以要設(shè)定為無限循環(huán)while True
#每行結(jié)尾有一個n,也被讀取
例:
file = open('passwd')
while True:
text = file.readline()
if not text:
break
print text
file.close()
四.讀取二進制文件時:
文件打開方式對應(yīng)為'r' –> mode='rb'
例:
f1 = open('hello.jpg', mode='rb')
f2 = open('happy.jpg', mode='wb')
content = f1.read()
f2.write(content)
f1.close()
f2.close()
練習示例:
1.創(chuàng)建文件data.txt,文件共10行,每行存放一個1—100之間的整數(shù)
import random
f = open('data.text','w+')
for i in range(10):
content = f.read()
a = random.randint(1, 100)
f.write('%dn' % a)
print content
f.close()
2.1).生成一個大文件ips.txt,要求1200行,每行隨機為172.25.254.0/24段的ip
2).讀取ips.txt文件統(tǒng)計這個文件中ip出現(xiàn)頻率排前十的ip
import random
def new_file(fileName):
file = open(fileName, 'w+')
content = file.read()
for i in range(1200):
a = random.randint(1, 254)
file.write('172.25.254.%d' % a +'n')
print content
file.close()
def top_ten_ip(filename,count = 10):
ips_dict = dict()
with open(filename) as file:
for ip in file:
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
input = raw_input('請輸入文件名:')
new_file(input)
print top_ten_ip(input)