python基礎 3.0 file 讀取文件


一.python  文件訪問
1.在python中要訪問文件,首先要打開文件,也就是open
r:  只讀
w:  只寫 ,文件已存在則清空,不存在則創建
a:追加 ,寫到文件末尾。如果文件存在,則在文件最后去追
    加。文件不存在就去創建   
+-:更新(可讀可寫)
 
r+ :以讀寫模式打開
w+ :以讀寫模式打開(參見w)
a+:以讀寫模式打開(參見a)
rb:以二進制讀模式打開
wb:以二進制寫模式打開
ab:以二進制追加模式打開(參見a)
rb+:以二進制讀寫模式打開(參見r+)
wb+:以二進制讀寫模式打開(參見w+)
ab+: 以二進制讀寫模式打開(參見a+)
 
2.打開文件。open打開文件 read讀文件,close關閉文件
 
import codecs
fd = codecs.open('2.txt')
print fd.read()
fd.close()
 
>>> 11111
2222
33333
aaaaa
bbbbb
cccccc
 
3.查看文件有哪些方法
 
import codecs
fd = codecs.open('b.txt')
print fd.read()
print dir(fd)
fd.close()
 
>>> 11111
2222
333333
['close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
 
1>fd.read() 方法,read()方法讀取的是整篇文檔。
 
fd = codecs.open('2.txt')
text = fd.read()
print type(text)
 
>>><type 'str'>
 
 
2>replace()函數替換文件中的某個元素。打開文件,讀取后,對整個字符串進行操作.把2.txt 文件中的1替換成z
 
fd = codecs.open('2.txt')
a1 = fd.read()
print a1
a2 = a1.replace('1','z')
print a2
 
>>> 11111
2222
33333
aaaaa
bbbbb
cccccc
 
zzzzz
2222
33333
aaaaa
bbbbb
cccccc
 
3> 寫文件,codecs.open()函數,避免文件亂碼
 
fd = codecs.open('3.txt','w')
fd.write('liuzhenchuan\n')
fd.write('hello world\n')
fd.write('xiaban\n')
fd.close()
 
>>> liuzhenchuan
hello world
xiaban
 
 
4>fd.readlines()方法,讀取文件,最后把文件每行內容作為一個字符串放在一個list中
 
fd = open('3.txt')
print fd.readlines()
fd.close()
 
>>> ['liuzhenchuan\n', 'hello world\n', 'xiaban\n']
 
 
5>fd.readline()方法,讀取文件,讀取文件一行,類型為字符串
>>> l
 
 
6>#fd.readline()方法,讀取文件一行內容,返回一個字符串.          # fd.next()方法,讀取文件下一行內容,返回一個字符串
 
fd = codecs.open('3.txt','r')
print fd.readline()
print fd.next()
fd.close()
 
>>> liuzhenchuan
 
    hello world
 
 
7>#write()方法,必須傳入一個字符串. 
fd = codecs.open('5.txt','w+')
fd.write('a\nb\nc\n')
fd.close()
 
>>> a
    b
    c
 
 
#writelines()方法,必須傳入一個列表/序列
fd = codecs.open('6.txt','w')
fd.writelines(['123\n','234\n','345\n'])
fd.close()
 
>>> 123
    234
    345
 
 
8>with用法,不需要用fd.close()關閉文件
with codecs.open('3.txt','rb') as fd:
    print fd.read()
    fd.close()
 
>>> liuzhenchuan
hello world
xiaban
 
 
9>打印文件行號和文件內容
with codecs.open('2.txt') as fd:
    for line,value in enumerate(fd):
        print line,value,
 
>>> 0 liuzhenchuan
    1 hello world
    2 xiaban
 
 
10>過濾文件某行的內容
with codecs.open('3.txt') as fd:
    for line,value in enumerate(fd):
        if line == 3-2:
            print value
 
>>> hello world
 
 
11>導入linecache模塊,使用linecache.getline()方法,獲取文件固定行的內容
import linecache
count = linecache.getline('3.txt',1)
print count
 
>>> liuzhenchuan
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM