python文件使用的基本方法

打開文件
f = open(filename, mode = ‘rt’)

mode
‘r’ -> read
‘w’ -> write
‘x’ -> 獨佔write
‘a’ -> append,加在文件尾部
可混合使用的
‘b’ -> binary mode
‘t’ -> 文本模式
‘+’ -> 讀寫模式

basic operations
read(n) -> return str with length of 5 chars
readline() -> return str
readlines() -> return list

write()
writelines(list)
(無writeline,因其等同於write,不再設writeline)

close() -> write in the data, and close the file

with as

with open(filename) as f:
    operations...
# 取文件的後五列
def read_last_five_col(filename):
	with open(filename, "r") as f:
	    res = ""
	    # process by lines
	    for line in f.readlines():
	        res += line[-6:-1]
	        res += "\n"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章