Python文件讀寫基本操作

文件讀寫是每一門編程語言的最基本的核心功能,有了文件讀寫功能,才能方便地存儲(chǔ)和讀取數(shù)據(jù)。

文件讀寫

假如當(dāng)前工作目錄為/mypy/,在該目錄下有一個(gè)文本文件:test.txt,其內(nèi)容為:

www.test.com
hello

打開文件

  • 方法1:
f = open('/mypy/test.txt')
print f
# 輸出:<open file 'test.txt',mode 'r' at...>
# 注:如果打開文件的時(shí)候不指定模式,默認(rèn)以`r`模式打開,表示只讀
  • 方法2:
f = file('test.txt')
print f
# 輸出:同上

可見,file()函數(shù)和open()函數(shù)有著相似的功能。

讀取文件內(nèi)容

f = open('test.txt')
print f.read()

輸出:

www.test.com
hello

關(guān)閉文件

文件使用完了之后,必須關(guān)閉:

f.close()

向文件中寫入內(nèi)容

f = open('test.txt')
f.write('new')
# 報(bào)錯(cuò):IOError: File not open for writing

這樣寫入內(nèi)容報(bào)錯(cuò)的原因是,以只讀方式打開的文件不允許寫入內(nèi)容,而要這樣:

f = open('test.txt','w+')
f.write('new')

執(zhí)行上面代碼,發(fā)現(xiàn)這次沒有報(bào)錯(cuò),可是去看test.txt文件的內(nèi)容,并沒有新寫入的new,這是為何呢?是因?yàn)檫€沒有執(zhí)行f.close()操作,所以文件還并沒有被保存,再執(zhí)行一下f.close()操作,現(xiàn)在再去看文件內(nèi)容,發(fā)現(xiàn)為:

new.test.com
hello

雖然把最新內(nèi)容new寫入了文件,但是卻是覆蓋了文件的前三個(gè)字符,這不是我們想要的,我們想把內(nèi)容寫到文件末尾,這里牽扯到文件指針的問題(后面講),要達(dá)到這個(gè)目的,需要這樣做:

f = open('test.txt')
f.read()
f.write('new')
f.close()

再次執(zhí)行上述操作,發(fā)現(xiàn)文件test.txt的末尾成功新增一行new。

文件讀寫模式

模式 含義
r 只讀
r+ 讀寫
w 寫入,先刪除原文件,再重新創(chuàng)建并寫入,若文件不存在則創(chuàng)建
w+ 讀寫,先刪除原文件,再重新創(chuàng)建并寫入,若文件不存在則創(chuàng)建
a 寫入,在文件末尾追加新內(nèi)容,若文件不存在則創(chuàng)建
a+ 讀寫,在文件末尾追加新內(nèi)容,若文件不存在則創(chuàng)建
b 打開二進(jìn)制文件,可與r,w,a,+結(jié)合使用,如:wb+
U 支持所有換行符:\r, \n, \r\n,可與r,w,a,+結(jié)合,但必須以r開頭,如'rUa+', 'rUw+'

注:以'w'、'a'模式打開文件,只支持寫入,不支持讀。

用with語句操作文件

打開文件,推薦使用上下文管理器with語句,它可以自動(dòng)管理文件的打開和關(guān)閉,用了它以后就不需手工關(guān)閉文件,并且支持一次打開多個(gè)文件,非常方便,標(biāo)準(zhǔn)用法如下:

with open('test1.txt','w+') as f1, open('test2.txt','w+') as f2:
  f1.write('123')
  f2.write('456')

文件對象常用函數(shù)

open

打開一個(gè)文件,其實(shí)file()函數(shù)也可以打開一個(gè)文件,但是推薦首先open()函數(shù)。open()函數(shù)返回一個(gè)file對象,是一個(gè)可迭代對象,例如依次讀取并輸出一個(gè)文件的每一行的內(nèi)容:

f = open('file.txt')
for line in f:
  print line

read

若不傳入?yún)?shù),表示從當(dāng)前文件指針?biāo)谖恢米x到文件末尾;若傳入一個(gè)表示size的參數(shù),表示從當(dāng)前文件指針?biāo)谖恢猛笞xsize個(gè)字節(jié),例如:

f = open('file.txt')
# 從開頭往后讀3個(gè)字節(jié)
f.read(3)
# 從第3個(gè)字節(jié)處往后讀5個(gè)字節(jié)
f.read(5)
# 從第8個(gè)字節(jié)處讀到文件末尾
f.read()

close

關(guān)閉文件:

f = open('file.txt')
f.close()

readline

每次讀文件的一行,如果不傳入任何參數(shù),表示每次讀一行的所有字符;如果傳入一個(gè)表示字節(jié)的size參數(shù),表示讀一行的前size個(gè)字節(jié),如果上一次本行沒有讀完,則下一次會(huì)接著讀,直到行尾。

readlines

返回一個(gè)列表,是包含一個(gè)文件的每一行內(nèi)容的字符串列表。

next

返回文件的下一行。

write

往文件中從當(dāng)前文件指針處寫入內(nèi)容。

writelines

傳入一個(gè)字符串列表參數(shù),將該字符串列表寫入文件。

flush

修改文件內(nèi)容后,提交更新。

seek(偏移量, 選項(xiàng))

  • 選項(xiàng) = 0:把文件指針從文件頭部向后(不能向前)移動(dòng)偏移量那么多的字節(jié)。
  • 選項(xiàng) = 1:把文件指針從當(dāng)前位置向后(不能向前)移動(dòng)偏移量那么多的字節(jié)。
  • 選項(xiàng) = 2:把文件指針從文件尾部向前移動(dòng)偏移量那么多的字節(jié)。

一個(gè)原則:移動(dòng)不能越界,否則會(huì)出錯(cuò)。

一個(gè)例子:將文件指針移到文件開頭:

f = open('file.txt')
f.seek(0,0)

os模塊常用函數(shù)

os模塊有很多實(shí)用的文件、目錄和路徑操作相關(guān)的函數(shù),下面介紹幾個(gè)最經(jīng)常用到的。

os.system()

基于當(dāng)前目錄執(zhí)行shell命令,并返回命令的執(zhí)行結(jié)果。函數(shù)原型:

Docstring:
system(command) -> exit_status

Execute the command (a string) in a subshell.
Type:      builtin_function_or_method

os.mkdir()

創(chuàng)建目錄,函數(shù)原型:

mkdir(path [, mode=0777])

Create a directory.
Type:      builtin_function_or_method

舉例:

# 在當(dāng)前目錄下創(chuàng)建名為dir1的目錄
os.mkdir('dir1')
# 使用該方法創(chuàng)建嵌套多層目錄會(huì)報(bào)錯(cuò)
os.mkdir('a/b/c')
# 列出path頂層目錄下的文件和文件夾(隨機(jī)順序)
os.listdir(path)

os.makedirs()

創(chuàng)建多級(jí)目錄,函數(shù)原型:

Signature: os.makedirs(name, mode=511)
Docstring:
makedirs(path [, mode=0777])

Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist.  This is
recursive.
File:      e:\code\env\.env\lib\os.py
Type:      function

os.rmdir()

刪除目錄(需要是空目錄),函數(shù)原型:

Docstring:
rmdir(path)

Remove a directory.
Type:      builtin_function_or_method

示例:

os.mkdir('dir1')
# 刪除目錄dir1
os.rmdir('dir1')

os.makedirs('a/b/c')
# c目錄被刪掉(若path為多級(jí)目錄,則只有最低一級(jí)的目錄被刪掉)
os.rmdir('a/b/c')

# 刪除失敗,提示:OSError: Directory not empty:a,目錄非空,無法刪除
os.rmdir('a')

os.removedirs()

刪除空的多級(jí)目錄(目錄中沒有文件),函數(shù)原型:

Signature: os.removedirs(name)
Docstring:
removedirs(path)

Super-rmdir; remove a leaf directory and all empty intermediate
ones.  Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs.  Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.
File:      e:\code\env\.env\lib\os.py
Type:      function

示例:

os.makedirs('a/b/c')
# 將'a/b/c'三級(jí)目錄同時(shí)刪掉
os.removedirs('a/b/c')

os.makedirs('a/b/c')
# 然后在'a/b'目錄下創(chuàng)建一個(gè)名為'file.txt'的文件
# 發(fā)現(xiàn)這時(shí)只有c目錄能被刪掉,a、b目錄及file.txt文件都還在
os.removedirs('a/b/c')

# 報(bào)錯(cuò):OSError: Directory not empty:'a/b'
os.removedirs('a/b')

os.getcwd()

獲取當(dāng)前的工作目錄,函數(shù)原型:

Docstring:
getcwd() -> path

Return a string representing the current working directory.
Type:      builtin_function_or_method

os.chdir()

修改當(dāng)前的工作目錄,影響os.getcwd()函數(shù)的返回值,函數(shù)原型:

Docstring:
chdir(path)

Change the current working directory to the specified path.
Type:      builtin_function_or_method

os.path的幾個(gè)實(shí)用函數(shù)

  • os.path.isabs()
    判斷某個(gè)路徑是否是一個(gè)絕對路徑。

  • os.path.isdir()
    判斷某個(gè)路徑是否是一個(gè)存在的路徑。

  • os.path.isfile()
    判斷某個(gè)路徑是否是一個(gè)文件。

  • os.path.islink()
    判斷某個(gè)路徑是否是一個(gè)超鏈接。但注意到函數(shù)說明中有這么一句話:

Signature: os.path.islink(path)
Docstring:
Test for symbolic link.
On WindowsNT/95 and OS/2 always returns false

WindowsNT/95OS/2系統(tǒng),os.path.islink()函數(shù)總是返回false

  • os.path.ismount()
    判斷某個(gè)路徑是否是一個(gè)掛載點(diǎn):
Test whether a path is a mount point (defined as root of drive)
  • os.path.abspath()
    以當(dāng)前工作目錄為前綴,把一個(gè)相對路徑轉(zhuǎn)為絕對路徑。

  • os.path.basename()
    獲取一個(gè)路徑代表的文件名(包括后綴名)。

  • os.path.exists()
    判斷某個(gè)路徑是否存在(可以為目錄路徑也可以為文件路徑)。

  • os.path.join(path1,*path)
    拼接2個(gè)或多個(gè)路徑,若其中一個(gè)為絕對路徑,那它之前的路徑都會(huì)被忽略。

os.walk(top, topdown = True, onerror = None)

遍歷根目錄top,遞歸地返回一個(gè)三元組:

(root, dirs, files)

其中,root為根目錄路徑,dirsroot路徑下的目錄列表,filesroot路徑下的文件列表。

topdown參數(shù)表示是否從頂層目錄開始遍歷,onerror是發(fā)生錯(cuò)誤時(shí)候的回調(diào)函數(shù)。

函數(shù)原型:

Directory tree generator.

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple

    dirpath, dirnames, filenames

dirpath is a string, the path to the directory.  dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).

If optional arg 'topdown' is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down).  If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).

When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune the
search, or to impose a specific order of visiting.  Modifying dirnames when
topdown is false is ineffective, since the directories in dirnames have
already been generated by the time dirnames itself is generated. No matter
the value of topdown, the list of subdirectories is retrieved before the
tuples for the directory and its subdirectories are generated.

By default errors from the os.listdir() call are ignored.  If
optional arg 'onerror' is specified, it should be a function; it
will be called with one argument, an os.error instance.  It can
report the error to continue with the walk, or raise the exception
to abort the walk.  Note that the filename is available as the
filename attribute of the exception object.

By default, os.walk does not follow symbolic links to subdirectories on
systems that support them.  In order to get this functionality, set the
optional argument 'followlinks' to true.

Caution:  if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk.  walk never
changes the current directory, and assumes that the client doesn't
either.

Example:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum([getsize(join(root, name)) for name in files]),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
File:      e:\code\env\.env\lib\os.py
Type:      function
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容