一.文件操作三部曲:
1.打開(kāi):
f = open('文件名')
文件名后不加任何時(shí),默認(rèn)是r以只讀的方法打開(kāi)
r:只能讀,不能寫(xiě)。讀取文件不存在時(shí)會(huì)報(bào)錯(cuò)
r+:可讀,可寫(xiě)。讀取文件不存在時(shí)會(huì)報(bào)錯(cuò)
w:只能寫(xiě),不能讀。文件存在時(shí),會(huì)清空文件覆蓋文件內(nèi)容;文件不存在時(shí),會(huì)新建文件。
w+:可寫(xiě),可讀。文件存在時(shí),會(huì)清空文件覆蓋文件內(nèi)容;文件不存在時(shí),會(huì)新建文件。
a:只能寫(xiě),不能讀。文件存在時(shí),不會(huì)清空文件內(nèi)容;文件不存在時(shí),新建文件不報(bào)錯(cuò)。
a+:可寫(xiě),可讀。文件存在時(shí),不會(huì)清空文件內(nèi)容;文件不存在時(shí),新建文件不報(bào)錯(cuò)。
2.操作:
讀:content = f.read()
##read()讀取整個(gè)文件
##readline()只讀取一行
print content
寫(xiě):f.write('寫(xiě)入內(nèi)容')
3.關(guān)閉:
f.close()
vcmV2ZXJfeWg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70″ />
二.文件指針:
文件指針標(biāo)記從哪個(gè)位置開(kāi)始讀取數(shù)據(jù)
第一次打開(kāi)文件時(shí),通常文件指針會(huì)指向文件的開(kāi)始位置,當(dāng)執(zhí)行了read方法后,文件指針會(huì)移動(dòng)到讀取內(nèi)容的末尾(文件指針指到了文件的最后一行,就讀取不到文件的內(nèi)容)。
三.讀取大型文件時(shí):
因?yàn)椴恢姥h(huán)的條件,不知道文件到底有多少行,所以要設(shè)定為無(wú)限循環(huán)while True
#每行結(jié)尾有一個(gè)n,也被讀取
例:
file = open('passwd')
while True:
text = file.readline()
if not text:
break
print text
file.close()
四.讀取二進(jìn)制文件時(shí):
文件打開(kāi)方式對(duì)應(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()
練習(xí)示例:
1.創(chuàng)建文件data.txt,文件共10行,每行存放一個(gè)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).生成一個(gè)大文件ips.txt,要求1200行,每行隨機(jī)為172.25.254.0/24段的ip
2).讀取ips.txt文件統(tǒng)計(jì)這個(gè)文件中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('請(qǐng)輸入文件名:')
new_file(input)
print top_ten_ip(input)