1. 程式人生 > >Python之輸入輸出

Python之輸入輸出

Python輸入輸出

1. print與input

print的基本用法

print()是python的基本輸出函式,它有著非常靈活的使用方法,下面通過help()檢視print的基本用法,在互動編輯介面輸入help(print)

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    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.

可以看到,print的引數為以下幾項:

  • value, …要列印的值, 以逗號分隔。
  • sep分隔符,預設以空格分隔(列印的每項之間以空格分開)。
  • end結束符, 預設為換行符(print預設會換行)。
  • file列印的目的物件,預設為標準輸出(可以改為其他的類似檔案的物件)。
  • flush是否立即輸出到file指定的流物件中。

(1) 資料型別
value可以是不同的資料型別,通過逗號將各資料項分開。

>>> print("Hello World!", "2018/11/18", 3.14)
Hello World! 2018
/11/18 3.14

(2) 更改分隔符
從上一個例子可以看出,輸出的各項以空格進行分隔。更改seq值可以更改分隔符型別,如下:

>>> print("Hello World!", "2018/11/18", 3.14, sep='#')
Hello World!#2018/11/18#3.14

(3) 更改結束符
下面這個例子:

>>> print("Hello World!")
... print("Hello World!")
Hello World!
Hello World!

可以看出,print預設以換行符結束。這裡可以通過更改end值更改結束符,如下:

>>> print("Hello World!", end=' ')
... print("Hello World!", end=' ')
Hello World! Hello World!

(4) 更改輸出位置
print預設輸出到標準輸出,我們可以通過file引數來更改輸出,如下:

f=open("out.txt", "w")
print("Hello World!", file=f)
f.close()

這裡更改輸出為out.txt,開啟out.txt檔案可以看到裡面的內容為Hello World!.
值得注意的是,print是不會立即輸出到out.txt檔案中的,它將要列印的資料保留再緩衝區,當執行到f.close()時才將資料寫入檔案中。如果需要立即列印到檔案中,將flush引數改為true即可。

input的基本用法

同樣的,我們先通過help命令檢視input的用法,在互動編輯介面輸入help(input),得到如下結果:

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

可以看出,input從標準輸入讀取一個字串,並去掉最後的換行符。此外,input的prompt引數可同於列印提示資訊。注意這裡讀取的任何內容都會被轉換為字串。

>>> a=input("Input:")
Input:Hello World!
>>> type(a)
<class 'str'>
>>> b=input("Input:")
Input:123
>>> type(b)
<class 'str'>

如果需要讀取整數,利用int進行強制轉換即可:

>>> c=int(input("Input:"))
Input:123
>>> type(c)
<class 'int'>

小結

1. print可以列印不同的資料型別,且不需要指定資料型別。
2. print輸出時各項之間預設以空格分隔,以換行符結尾,可以通過sepend引數更改。
3. print預設輸出到標準輸出,可通過file引數更改。
4. Input將讀取的資料轉換為字串。

2. 檔案讀寫操作

開啟關閉檔案

開啟檔案的函式為open(),利用help可檢視其用法,由於介紹過長,下面僅貼出一部分:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise IOError upon failure.

從介紹可以看出,open()的作用是開啟檔案,返回一個流物件,如果失敗則丟擲錯誤。引數的意義如下:
[file] 檔案物件,文字檔案或者是二進位制檔案。
[mode] 開啟模式(讀、寫、追加、文字檔案、二進位制檔案等),預設為"讀文字"。
[encoding] 編碼方式,預設值與平臺無關。
[errors] 指定編碼錯誤的處理方式。
[newline] 設定換行的方式(None、’\n’、’\r’和’\r\n’)
其中,mode的取值如下:

Character Meaning-
‘r’ 讀 (預設)
‘w’
‘x’ 新建檔案,寫
‘a’ 在檔案末尾追加
‘b’ 二進位制模式
‘t’ 文字模式(預設)
‘+’ 讀寫(不單獨存在)
‘U’ 通用換行符

可通過上述的組合實現不同的模式,如rb(二進位制讀)、w+(讀寫)等。
注意:**利用open()開啟檔案之後需要用f.close()關閉檔案。**也可以使用如下方式開啟檔案,則不需要手動關閉檔案:

with open("data.txt") as f:
	pass

讀檔案

f.read
f.read用於讀取檔案中指定位元組數的資料,如果不指定位元組數,則預設讀取檔案中所有內容。

with open("data.txt") as f:
    print(f.read())
Line one: Hello World!
Line two: Hello World!
Line three: Hello World!
Line four: Hello World!

f.readline
f.readline用於讀取檔案中的一行。

with open("data.txt") as f:
    print(f.readline())
Line one: Hello World!

f.readlines
f.readline用於讀取檔案中所有行。預設返回為所有行構成的list。

with open("data.txt") as f:
    ret = f.readlines()
    print(type(ret))
    print(ret)
<class 'list'>
['Line one: Hello World!\n', 'Line two: Hello World!\n', 'Line three: Hello World!\n', 'Line four: Hello World!']

此外,還可以通過迭代物件來讀取所有行。

with open("data.txt") as f:
    for line in f:
        print(line, end='')
Line one: Hello World!
Line two: Hello World!
Line three: Hello World!
Line four: Hello World!

寫檔案

f.write
f.write用於將字串寫入到檔案中,返回寫入的位元組數。

with open("data.txt", "w") as f:
    print(f.write("Hello World!"))
12

其他檔案操作

f.tell
f.tell用於返回檔案指標當前的位置(距離檔案起始位置的位元組數)

with open("data.txt", "r") as f:
    f.read(5)
    print(f.tell())
5

f.seek
f.seek用於移動檔案指標到指定的位置。用法如下:

seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
    Change stream position.

    Change the stream position to the given byte offset. The offset is
    interpreted relative to the position indicated by whence.  Values
    for whence are:

    * 0 -- start of stream (the default); offset should be zero or positive
    * 1 -- current stream position; offset may be negative
    * 2 -- end of stream; offset is usually negative

它有兩個引數,第一個是偏移量cookie,第二個是起始位置whence。起始位置可以是檔案起始位置(0)、當前位置(1), 檔案尾(2)。
例子如下:

with open("data.txt", "r") as f:
    f.seek(5)//移動到位置5
    print(f.read())//讀取所有內容
 World!