python語言IO編程

一、文件讀寫

1、文件的打開和關(guān)閉。在python語言中,文件的打開和關(guān)閉分別使用的是open函數(shù)和close函數(shù),兩者一般是配套使用。

open + close模式:需要手動編寫關(guān)閉文件代碼,如果沒有手動關(guān)閉文件,會引發(fā)一系列的問題。

f = open('text.txt',encoding='utf8')
print(f.read())
f.close() #需要手動關(guān)閉文件
你好

with + open模式:這種模式下,不需要在手動編寫關(guān)閉文件的程序代碼(f.close()),程序會在執(zhí)行完with結(jié)構(gòu)體中的程序后自動關(guān)閉打開的文件。

with open('text.txt',encoding='utf-8') as f:
    print('讀取文件信息:',f.read())
    
print('再次嘗試讀取文件:',f.read()) #文件已經(jīng)被關(guān)閉,讀取失敗
讀取文件信息: 你好
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-dbc1a27d9d7b> in <module>
      2     print('讀取文件信息:',f.read())
      3 
----> 4 print('再次嘗試讀取文件:',f.read())

ValueError: I/O operation on closed file.

2、open方法調(diào)用語法:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

參數(shù):

  • file:必填,文件路勁(相對路徑或者絕對路徑)
  • mode:可選,文件打開模式
  • buffering:設(shè)置緩沖
  • encoding:一般設(shè)置為‘utf8’
  • errors:報錯級別
  • newline:區(qū)分換行符
  • closefd:傳入的file參數(shù)類型
  • opener:可選

文件打開模式mode:

方法 含義 解釋
r read 讀?。J(rèn))
w write 截斷寫入
a append 在原內(nèi)容后追加寫入
x exclusive 獨占寫入,文件存在會報錯
b binary 二進制模式
t text 文本模式(默認(rèn))
+ 擴展 擴展為讀寫模式

mode='rt'模式:這是文件打開默認(rèn)模式,比如:

with open('text.txt',encoding='utf-8') as f:
    print('讀取文件信息:',f.read())
讀取文件信息: 你好

上例等效于:

with open('text.txt',mode='rt',encoding='utf-8') as f:
    print('讀取文件信息:',f.read())
讀取文件信息: 你好

mode='w'模式:它會將覆蓋掉原來的數(shù)據(jù),所以使用時需要小心。比如:

with open('text.txt',mode='w',encoding='utf-8') as f:
    f.write('hello world!')
    
with open('text.txt',mode='rt',encoding='utf-8') as f:
    print('讀取文件信息:',f.read())
讀取文件信息: hello world!

上例,原文件信息為“你好”,但在“截斷寫入w”模式下寫入下,文件中保存到信息被覆蓋,現(xiàn)在文件信息為:hello world!所以使用“截斷寫入w”模式時需要非常小心。

mode='a'模式:追加模式,它會保留原來文件信息,并在文件末尾追加新的信息。

with open('text.txt',mode='a',encoding='utf-8') as f:
    f.write('這是追加的內(nèi)容')
    
with open('text.txt',mode='rt',encoding='utf-8') as f:
    print('讀取文件信息:',f.read())
讀取文件信息: hello world!這是追加的內(nèi)容

mode='x'模式:它會創(chuàng)建一個新文件,并寫入內(nèi)容,如果文件存在會報錯。

with open('text.txt',mode='x',encoding='utf-8') as f:
    f.write('這是獨占寫入模式')
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-21-d1aaaa94b779> in <module>
----> 1 with open('text.txt',mode='x',encoding='utf-8') as f:
      2     f.write('這是獨占寫入模式')

FileExistsError: [Errno 17] File exists: 'text.txt'

錯誤提示,文件已經(jīng)存在了。

3、讀寫方法

方法 作用
read([size]) 讀取指定字節(jié)的內(nèi)容
readline([size]) 讀取一行內(nèi)容
readlines([size]) 讀取多行內(nèi)容,返回列表
write(s) 寫入字符串
writelines(s) 寫入數(shù)據(jù),支持字符串也支持列表
tell() 獲取當(dāng)前文件位置
seek(n) 移動文件位置
close() 關(guān)閉文件

read方法:讀取指定字節(jié)的內(nèi)容,顯示的是字符串。

with open('text.txt',mode='r',encoding='utf-8') as f:
    print(type(f.read()))
    f.seek(0)#文件指針回到初始位置
    print("讀取到的內(nèi)容為:",f.read())
    
<class 'str'>
讀取到的內(nèi)容為: hello world!這是追加的內(nèi)容
123
456
789

readlines方法:讀取多行內(nèi)容,返回的是列表。

with open('text.txt',mode='r',encoding='utf-8') as f:
    print(type(f.readlines()))
    f.seek(0)#文件指針回到初始位置
    print("讀取到的內(nèi)容為:",f.readlines())
<class 'list'>
讀取到的內(nèi)容為: ['hello world!這是追加的內(nèi)容\n', '123\n', '456\n', '789']

readline方法:讀取一行內(nèi)容。

with open('text.txt',mode='r',encoding='utf-8') as f:
    print(type(f.readline()))
    f.seek(0)#文件指針回到初始位置
    print("讀取到的內(nèi)容為:",f.readline())
<class 'str'>
讀取到的內(nèi)容為: hello world!這是追加的內(nèi)容

writelines方法:將列表寫入。

with open('text.txt',mode='a+',encoding='utf-8') as f:
    f.writelines(['123','你好'])
    f.seek(0)
    print(f.read())
hello world!這是追加的內(nèi)容
123
456
789123123123123123123123你好

write方法:將字符串寫入,注意寫的是字符串。

with open('text.txt',mode='a+',encoding='utf-8') as f:
    f.write(['123','你好'])
    f.seek(0)
    print(f.read())
TypeError: write() argument must be str, not list

tell方法:獲取當(dāng)前文件位置。

with open('text.txt',mode='r',encoding='utf-8') as f:
    print("讀取到的內(nèi)容為:",f.readline())
    print("當(dāng)前指針位置為:",f.tell())
    print("讀取到的內(nèi)容為:",f.readline())
    print("當(dāng)前指針位置為:",f.tell())
讀取到的內(nèi)容為: key1kye2

當(dāng)前指針位置為: 9
讀取到的內(nèi)容為: hello world!這是追加的內(nèi)容

當(dāng)前指針位置為: 43

二、輸入和輸出

1、input函數(shù)

input()函數(shù)有且只有一個參數(shù),在執(zhí)行input() 函數(shù)時會暫停程序運行,同時等待鍵盤輸入;直到回車被按下,函數(shù)的參數(shù)即為提示輸入的類型永遠(yuǎn)是字符串型(str)。這里尤其需要注意。

a = input() #輸入1
print(type(a))
1
<class 'str'>

如果沒有注意input函數(shù)輸入的類型是字符串,那可能會導(dǎo)致如下錯誤,比如在進行數(shù)字計算時。

a = input() #輸入1
b = input() #輸入2
print(a + b)#按理說應(yīng)該是1 + 2 = 3,但結(jié)果顯示的是12,這其實是字符串的拼接導(dǎo)致。
1
2
12

2、print函數(shù)

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

參數(shù):

  • value:是帶輸出的內(nèi)容。
  • sep:內(nèi)容的分隔符。
  • end:內(nèi)容結(jié)尾符號。
  • file:一個file-like對象,被輸出的流。
  • flush:是否強制刷新。

sep參數(shù):內(nèi)容的分隔符,默認(rèn)情況下是空格’‘進行分割。

print(1,2,"hello",(1,2,3))
1 2 hello (1, 2, 3)

上例是默認(rèn)情況下空格分隔,再看’-‘分割:

print(1,2,"hello",(1,2,3),sep='-')
1-2-hello-(1, 2, 3)

end參數(shù):內(nèi)容結(jié)尾符號,默認(rèn)情況下是換行符’\n‘。

print(1,2,"hello",(1,2,3))
print(1,2,"hello",(1,2,3))
1 2 hello (1, 2, 3)
1 2 hello (1, 2, 3)

輸出的內(nèi)容自動換行了,若把默認(rèn)換行符修改成空格,那么就顯示在一行:

print(1,2,"hello",(1,2,3),end='')
print(1,2,"hello",(1,2,3))
1 2 hello (1, 2, 3)1 2 hello (1, 2, 3)

還可以任意修改,比如結(jié)尾是三個???:

print(1,2,"hello",(1,2,3),end='???')
1 2 hello (1, 2, 3)???

file參數(shù):一個file-like對象,被輸出的流,默認(rèn)情況下值是sys.stdout,其實就是把想要輸出的內(nèi)容顯示的解釋器控制臺。

要理解sys.stdout,我們需要知道標(biāo)準(zhǔn)流的概念。背景如下(維基百科)

在Unix之前的操作系統(tǒng),程序必須明確指出鏈接到合適的輸入和輸出數(shù)據(jù)。對這當(dāng)中的許多系統(tǒng)而言,這牽涉一些錯綜復(fù)雜而又與特定操作系統(tǒng)相關(guān)的事,是一件嚇人的程序設(shè)計挑戰(zhàn)。如控制環(huán)境設(shè)置、訪問一個文件表格、決定區(qū)域數(shù)據(jù)集、和決定讀卡器、磁帶、磁盤、打印機、打卡機或交互式終端機。

Unix 提供許多開創(chuàng)產(chǎn)的進步,其中之一是提供 抽象設(shè)備 :它免除了程序須要知道或在意它正與哪個設(shè)備溝通。 Unix 借由數(shù)據(jù)流的概念來消除這種復(fù)雜:一種數(shù)據(jù)字節(jié)的有序序列,直到讀到文件結(jié)尾。程序員亦可依需求寫入而無須宣告寫入多少或如何組織。

另一個 Unix 突破為默認(rèn)自動鏈接輸入和輸出-程序(和程序員)不用為了典型輸入-處理-輸出程序創(chuàng)建輸入和輸出。相對地,之前操作系統(tǒng)通常要求一些-有時復(fù)雜-工作控制語言Job Control Language)以創(chuàng)建鏈接,或者,相者近似于協(xié)調(diào)的責(zé)任。

既然 Unix 提供標(biāo)準(zhǔn)流,Unix C 的運行環(huán)境被要求要支持它。結(jié)果不管什么操作系統(tǒng), C 的運行環(huán)境(及 C 的派生)都提供類似功能。

python 中有三種標(biāo)準(zhǔn)輸入輸出流:sys.stdin(標(biāo)準(zhǔn)輸入)、sys.stdout(標(biāo)準(zhǔn)輸出)、sys.error(標(biāo)準(zhǔn)錯誤)

重定向

python中將標(biāo)準(zhǔn)輸出重定向到某個文件當(dāng)中

with open('text.txt',mode='w',encoding='utf8') as f:
    print("這是我要輸出的內(nèi)容",file=f)

結(jié)果沒有顯示,然后打開'text.txt'后,可以查看到輸出的信息。

輸入重定向到python程序當(dāng)中,比如有這樣一個程序:test.py

while True:
    text = input()
    print(text)

有這樣一個文本文件(txt.txt),信息如下:

hello world!
hello
123
456

在cmd命令環(huán)境下執(zhí)行python語句(python test.py < txt),輸入重定向到python程序當(dāng)中:

E:\python\WordCloudPro\mytest>python test.py < txt
hello world!
hello
123
456
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    text = input()
EOFError: EOF when reading a line

attempt to call a nil value

程序?qū)⑽谋疚募╰xt.txt)中的信息重定向到python程序中。

還可以在cmd命令環(huán)境下,把python程序中的輸出信息和錯誤信息分別重定向到不同文件中:

python test.py 1>1.txt 2>error.txt

把輸出信息定向到1.txt文件中,把錯誤信息重定向到error.txt文件中。

還可以在cmd命令環(huán)境下,把python程序中的輸出信息重定向到某個文件中:

python test.py 1>1.txt 2>&1
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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