python檔案操作

2021-08-07 19:39:21 字數 4697 閱讀 4931

關於檔案的開啟模式有以下標誌,需牢記!!!

python file(檔案) 方法

file 物件使用 open 函式來建立,下圖列出了 file 物件常用的函式:

in [0]: fo = open('/bao/file','wb')#開啟檔案

in [1]: fo.#檔案操作的方法

fo.close fo.flush fo.next fo.seek fo.writelines

fo.closed fo.isatty fo.read fo.softspace fo.xreadlines

fo.encoding fo.mode fo.readinto fo.tell

fo.errors fo.name fo.readline fo.truncate

fo.fileno fo.newlines fo.readlines fo.write

in [2]: fo.name#獲取檔案的名稱

out[2]: '/bao/file'

in [3]: fo.closed#判斷檔案是否關閉

out[3]: false

in [4]: fo.mode#獲取檔案的訪問模式

out[4]: 'wb'

in [5]: fo.softspace#判斷末尾是否強制加空格

out[5]: 0

in [6]: fo.close()#關閉檔案

in [7]: fo.closed#判斷檔案是否關閉

out[7]: true

in [10]: fo.write('halo')#向檔案中追加內容,如果不關閉的話內容還在快取中,需要關閉檔案或者使用flush方法使內容儲存到檔案中去

in [11]: fo.flush()#快取寫入

in [12]: fo.tell()#獲取檔案當前位置

out[12]: 10

in [13]: fo.seek(5)#將指標定位到檔案的某個位置

in [14]: fo.tell()

out[14]: 5

in [98]: fo.read()#讀取檔案的內容,預設讀取最大能讀取的位元組數,並且將操作指標移到最大位元組處

out[98]: 'halosdfsdfsdf\nsfdsfsdff\nsdfdsf\naaaaaaaaaaaaddddddddddddddddddsffsdf'

in [99]: fo.read(10)#因為上乙個操作已經將檔案指標移到檔案末尾,所以沒有剩餘內容可以讀取

out[99]: ''

in [100]: fo.tell()#獲取當前檔案操作指標的位置

out[100]: 67

in [101]: fo.seek(0)#將檔案操作指標重新定位到檔案開頭,然後再去讀取就ok了

in [102]: fo.read(10)#從檔案操作指標出開始讀取10個位元組的內容

out[102]: 'halosdfsdf'

in [109]: cat /bao/file

halosdfsdfsdf

sfdsfsdff

sdfdsf

aaaaaaaaaaaaddddddddddddddddddsffsdf

in [106]: fo.readline()#按行讀取檔案,再次操作的時候讀取下一行,類似生成器

out[106]: 'halosdfsdfsdf\n'

in [107]: fo.readline()

out[107]: 'sfdsfsdff\n'

in [108]: fo.readline()

out[108]: 'sdfdsf\n'

in [109]: fo.readline()

out[109]: 'aaaaaaaaaaaaddddddddddddddddddsffsdf'

in [110]: fo.readline()

out[110]: ''

in [114]: fo.readlines()#預設一次讀取盡可能多的行返回乙個列表儲存所有的行,每乙個行作為乙個列表的元素;如果傳遞乙個整形引數的話就讀取指定大小的內容後返回,這樣可以避免大檔案讀取造成的記憶體占用

out[114]:

['halosdfsdfsdf\n',

'sfdsfsdff\n',

'sdfdsf\n',

'aaaaaaaaaaaaddddddddddddddddddsffsdf']

in [122]: fo = open('/bao/file')

in [123]: p = fo.xreadlines()#獲得乙個檔案讀取的迭代物件

in [124]: p.next()#呼叫迭代物件逐個獲取檔案行

in [19]: from collections import iterable

in [20]: isinstance(fo,iterable)#判斷檔案物件是可迭代的

out[20]: true

in [21]: for i in fo:

....: print i

....:

daemon:x:2:2:daemon:/sbin:/sbin/nologin

#with 語句是從 python 2.5 開始引入的一種與異常處理相關的功能,可以用來安全開啟乙個檔案

in [29]: with open('/bao/file','r') as fo:

....: print fo.read()

....:

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

1. 過濾掉檔案中以#開頭的行:

def

filefilter

(fname):

fo = open(fname,'r+')

while

true:

line = fo.readlines(2)

ifnot line:

break

else:

for i in line:

stripline = i.strip()

ifnot stripline.startswith('#'):

print stripline

fo.close()

2.根據使用者輸入的讀取行數,然後判斷使用者的讀取行為(繼續還是退出)來顯示文字中每一次讀取的內容:

def

fileread

():while

true:

filename = raw_input('please input file name(q to quit): ')

if filename in

'qq':

return

try:

fo = open(filename,'r')

lines = raw_input('please input read lines(q to quit): ')

if lines in

'qq':

return

try:

lines = int(lines)

print

'1-%s lines contents as below:\n'%lines

for i in range(0, lines):

print fo.readline().strip()

times = 0

while

true:

ynq = raw_input('\nsure to continue read file content[y/n]:')

if ynq in

'nn':

return

if ynq in

'yy':

ifnot fo.readline():

print

'file read to the end!'

return

times += 1

starts = lines * times

ends = starts + lines

print

'{}-{} lines contents as below:\n'.format(starts + 1, ends)

for i in range(starts, ends):

print fo.readline().strip()

fo.close()

except:

print

'illegal line number!'

except:

print

'no such file or permission denied!'

python 檔案操作

簡明 python 教程 中的例子,python 執行出錯,用open代替file 可以執行。poem programming is fun when the work is done if you wanna make your work also fun use python f open e ...

python檔案操作

1,將乙個路徑名分解為目錄名和檔名兩部分 a,b os.path.split c 123 456 test.txt print a print b 顯示 c 123 456 test.txt 2,分解檔名的副檔名 a,b os.path.splitext c 123 456 test.txt pri...

Python 檔案操作

1.開啟檔案 如下 f open d test.txt w 說明 第乙個引數是檔名稱,包括路徑 第二個引數是開啟的模式mode r 唯讀 預設。如果檔案不存在,則丟擲錯誤 w 只寫 如果檔案 不存在,則自動建立檔案 a 附加到檔案末尾 r 讀寫 如果需要以二進位制方式開啟檔案,需要在mode後面加上...