【Python學習筆記】Coursera之PY4E學習筆記——File
阿新 • • 發佈:2018-05-05
color 學習筆記 函數 read mod rom stephen 內容 filename
1、打開文件
使用handle=open(filename,mode)打開文件。這一函數將會返回一個handle(應該翻譯為“柄”吧)用來操控文件,參數filename是一個字符串。參數mode是可選的,‘r‘代表讀取文件,‘w‘代表寫文件。
例:
>>> fhand=open(‘mbox.txt‘,‘r‘)
>>> print(fhand)
<_io.TextIOWrapper name=‘mbox.txt‘ mode=‘r‘ encoding=‘UTF-8‘>
file handle可以看作是一個字符串序列,而文件例的每一行是這個字符串序列裏的內容。
例:數文件內容的行數
fhand=open(‘mbox.txt‘) count=0 for line in fhand: count=count+1 print(‘Line Count:‘,count) $ python open.py Line Count:132045
例:檢索文件內容
fhand = open(;mbox-short.txt‘) for line in fhand: if line.startswith(‘From:‘): print(line)
2、讀取文件
使用read()來讀取整個文件(包括換行符等),存入一個單獨的字符串。
例:
>>> fhand=open(‘mbox-short.txt‘) >>> inp=fhand.read() >>> print(len(inp)) 94626 >>> print(inp[:20]) From stephen.marquar
【Python學習筆記】Coursera之PY4E學習筆記——File