1. 程式人生 > >python知識整理(讀寫檔案)_4

python知識整理(讀寫檔案)_4

!#/usr/bin/python env
# -- conding --

awk -F ':'  '/OO/'  password
awk -F ':'  '$1~/root/'   password

讀寫檔案:  
1、新建一個檔案,並寫入內容,檔案不存在會自動建立。

test = 'This is my first file\n Thsi is line'

file=oepn('2.txt','w')                //w 如果檔案不存自動建立。
file.write(test)
file.close()

file.read()           檢視這個檔案:

如何給檔案增加內容:
file_append='\n this  is  file append'

file=open('2.txt','a')
file.write(test)
file.close()

掌握append的用法:   file=open('2.txt','a')     開啟型別為 a     a 則表示 append

3、讀取檔案內容:
file=open('2.txt','r')
content=file.read()
print(content)

按行讀取:
如果想在文件中一行一行的讀取,比如excel檔案:
讀取的內容和你使用的次數有關,如 使用第二次的時候,讀取的就是文字你的第二行:
存取到了一個 python list 裡面:

file = open('2.txt','r')

content = file.readline()
second_read_time = file.readline()
print(contend,second_read_time)

輸出所有行:     file.readline
 list 形式

file = open('2.txt','r')
content = file.readlines()
print(content)

附加:
如何只要求輸出指定的行:    比如只要第三行:
import   linecache
text = linecache.getline('2.txt'