file 文件

1.文件的讀取

讀取一個文件需要 打開文件->讀取文件->關閉文件

import codecs

f = codecs.open('text')          #打開文件

#print f.read()                  #讀取文件
text1 = f.read()
cc = text1.replace('a','A')      #替換文件中的a 爲A
print cc
print dir(f)     #查看所有文件的操作方式
f.close()        #關閉文件


2. 寫文件

codecs 模塊是解決文件亂碼文件

codecs.open(filename,mode)

  mode裏參數:r是讀 w是寫  a追加

import codecs

f = codecs.open('1.txt','w')        #寫一個1.txt的文件
f.write('hello world\n')            # 寫入內容
f.write('python is so easy\n') 
g = codecs.open('1.txt','a')        #打開追加
g.write('hello man\n')              #追加內容
g.write('feel so cool\n')

f.close()                           #關閉文件

print g                             


3. file的常用方法

_readlines()  

將文件中每行生成字符串在一個列表中。

import codecs
f = codecs.open('1.txt','rb')
#print dir(f)
#list1 = f.readlines()
#print (list1[0])
print f.readlines()
f.close()

_readline()

讀取文件一行的內容。讀取之後就不再讀取,重複讀取下一行。

import codecs
f = codecs.open('1.txt','rb')
print f.readline()      #第一行
print f.readline()      #第二行
print f.readline()      #第三行
print f.next()          #讀取下一行
f.close()

write() 必須寫入一個字符串,跟 read()類似

writelines()  必修寫入列表

f = open('file2','wb')
f.write('hello world\n biubiubiubiu\npython\nheiheihei\n')   #wirte直接寫
f.writelines(['aaaaaa\n','bbbbbbbbbb\n','cccccccc'])         # wirtelines要在列表裏寫
f.close()
這就是區別



f.tell() 當前有多少字符

f.seek(0) 0是開頭覆蓋掉前面的字符

import codecs
f = codecs.open('file2','wb')
f.write('hello world\n biubiubiubiu\npython\nheiheihei\n')
print (f.tell())

f.writelines(['aaaaaa\n','bbbbbbbbbb\n','cccccccc'])
f.seek(0)
f.write('learn python make me feel so cool')
file.flush()                          #刷新
print (file.name)                     #名字
print (file.closed)                   #檢查是否關閉 Flase
print (file.mode)                     #打開方式
f.close()
print (file.closed)                   # true 已關閉文件


4.file的with的用法

with....as.

如果不用with語句

f = codecs.open('1.txt','rb')
print (f.read())
f.close()


使用with語句

with codecs.open('1.txt','rb') as fd:
    print fd.read()
print fd.closed
使用with可以自動結束文件的句柄,還能處理異常。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章