python讀寫txt文件


整理平常經常用到的文件對象方法:

f.readline()   逐行讀取數據
方法一:

1 >>> f = open('/tmp/test.txt')
2 >>> f.readline()
3 'hello girl!\n'
4 >>> f.readline()
5 'hello boy!\n'
6 >>> f.readline()
7 'hello man!'
8 >>> f.readline()
9 ''

方法二:

 1 >>> for i in open('/tmp/test.txt'):
 2 ...   print i
 3 ...
 4 hello girl!
 5 hello boy!
 6 hello man!
 7 f.readlines()   將文件內容以列表的形式存放
 8  
 9 >>> f = open('/tmp/test.txt')
10 >>> f.readlines()
11 ['hello girl!\n', 'hello boy!\n', 'hello man!']
12 >>> f.close()

f.next()   逐行讀取數據,和f.readline() 相似,唯一不同的是,f.readline() 讀取到最后如果沒有數據會返回空,而f.next() 沒讀取到數據則會報錯

 1 >>> f = open('/tmp/test.txt')
 2 >>> f.readlines()
 3 ['hello girl!\n', 'hello boy!\n', 'hello man!']
 4 >>> f.close()
 5 >>>
 6 >>> f = open('/tmp/test.txt')
 7 >>> f.next()
 8 'hello girl!\n'
 9 >>> f.next()
10 'hello boy!\n'
11 >>> f.next()
12 'hello man!'
13 >>> f.next()
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 StopIteration

f.writelines()   多行寫入

 1 >>> l = ['\nhello dear!','\nhello son!','\nhello baby!\n']
 2 >>> f = open('/tmp/test.txt','a')
 3 >>> f.writelines(l)
 4 >>> f.close()
 5 [root@node1 python]# cat /tmp/test.txt
 6 hello girl!
 7 hello boy!
 8 hello man!
 9 hello dear!
10 hello son!
11 hello baby!

f.seek(偏移量,選項)

 1 >>> f = open('/tmp/test.txt','r+')
 2 >>> f.readline()
 3 'hello girl!\n'
 4 >>> f.readline()
 5 'hello boy!\n'
 6 >>> f.readline()
 7 'hello man!\n'
 8 >>> f.readline()
 9 ' '
10 >>> f.close()
11 >>> f = open('/tmp/test.txt','r+')
12 >>> f.read()
13 'hello girl!\nhello boy!\nhello man!\n'
14 >>> f.readline()
15 ''
16 >>> f.close()

這個例子可以充分的解釋前面使用r+這個模式的時候,為什么需要執行f.read()之后才能正常插入
f.seek(偏移量,選項)
(1)選項=0,表示將文件指針指向從文件頭部到“偏移量”字節處
(2)選項=1,表示將文件指針指向從文件的當前位置,向后移動“偏移量”字節
(3)選項=2,表示將文件指針指向從文件的尾部,向前移動“偏移量”字節

偏移量:正數表示向右偏移,負數表示向左偏移

 1 >>> f = open('/tmp/test.txt','r+')
 2 >>> f.seek(0,2)
 3 >>> f.readline()
 4 ''
 5 >>> f.seek(0,0)
 6 >>> f.readline()
 7 'hello girl!\n'
 8 >>> f.readline()
 9 'hello boy!\n'
10 >>> f.readline()
11 'hello man!\n'
12 >>> f.readline()
13 ''

f.flush()    將修改寫入到文件中(無需關閉文件)

>>> f.write('hello python!')
>>> f.flush()
hello girl!
hello boy!
hello man!
hello python!

f.tell()   獲取指針位置

1 >>> f = open('/tmp/test.txt')
2 >>> f.readline()
3 'hello girl!\n'
4 >>> f.tell()
5 12
6 >>> f.readline()
7 'hello boy!\n'
8 >>> f.tell()
9 23

 


免責聲明!

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



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