Python學習筆記9 檔案

2021-09-08 19:17:22 字數 2214 閱讀 2414

在python中,要對乙個檔案進行操作,只需用內建的open函式開啟檔案即可。

signature: open(file, mode='r', buffering=-1, encoding=none, errors=none, newline=none,closefd=true, opener=none)

docstring:

open file and return a stream. raise ioerror upon failure.

python內建的open函式:

關閉檔案:

開啟的檔案要及時關閉,在python中也可以使用finally語句來保證,但是卻不夠pythonic。

使用finally的方法:

使用上下文管理器,會自動呼叫close()方法

常見的檔案讀取的函式:

此時指標所在的位置,還可以用tell() 來顯示,如

>>> f.tell()

17

讀取大檔案的幾種方法:while 迴圈和readlin() 來完成這個任務。

#

/usr/bin/env python

#coding=utf-8

f = open("

/python/you.md")

while

true:

line =f.readline()

ifnot

line: #到 eof,返回空字串,則終止迴圈

break

print

line, #注意後面的逗號,去掉 print 語句後面的 '\n',保留原檔案中的換行

f.close()

還有乙個方法:fileinput 模組

>>> import

fileinput

>>> for line in fileinput.input("

you.md"):

...

print

line,

...

you raise me up

when i am down

and, oh my soul, so weary;

then troubles come

and my heart burdened be;

但是使用迭代的方法是最好的:因為 file 是可迭代的資料型別

經典案列:

將所有單詞首字母變為大寫:

使用write:

使用print,更加簡化:

Python學習筆記D9(檔案)

檔案 1.開啟檔案 open file,mode r 接收兩個引數 檔名 file 和模式 mode 用於開啟乙個檔案,並返回檔案物件,如果該檔案無法被開啟,會丟擲oserror。完整的語法格式為 open file,mode r buffering 1,encoding none,errors n...

python筆記9 檔案的操作

python中的io操作其實跟c語言比較類似 一.關於檔案的讀寫 開啟乙個檔案 以下列出了最常用的函式 fp open 模式 這裡的模式可以是r 讀 w 寫 a 追加 r 讀寫 w 讀寫 a 讀寫 ps linux系統下沒有二進位制檔案與文字檔案的區別 fp.read 讀取檔案內容 fp.readl...

LINUX學習筆記9 檔案訪問

a 建立檔案 int creat const char filename,mode t mode 1.filename 要建立的檔名 2.include include include 3.mode 建立模式 只能控制建立使用者的寫屬性,其餘使用者都是不可寫,所以一般是755 a s irusr 可...