Python 輸入和輸出

1、在控制檯上輸入、輸出python

inputvalue1 = input("please input:")
print(inputvalue1)
rawinputvalue1 = raw_input("the value of rawinputvalue1:")
print(rawinputvalue1)

結果:函數

please input:'hello'
hello
the value of rawinputvalue1:hello
hello

input嚴格遵照python的語法,如輸入字符串,則必須加上單引號,不然會報錯;spa

而raw_input不會有這些限制;code

2、文件對象

一、open函數打開文件blog

語法以下:教程

open(name[,mode[,buffering]]),文件名爲必填參數,模式和緩衝參數是可選的。內存

最簡單的示例以下:字符串

open(r'c:\text\file.txt')input

(1)模式mode

文件的模式做用是控制用戶讀、寫文件等權限;默認權限是讀模式,即參數mode沒有賦值時,用戶只能讀文件。

‘+’參數能夠用到其它任何模式中,指明讀和寫都是容許的。

(2)緩衝

若是參數是0(或者是false),I/O就是無緩衝的(全部的讀寫操做都直接針對硬盤);若是是1(或者是true),I/O就是有緩衝的(覺得這Python使用內存來代替硬盤,讓程序更快,只有使用flush或者close時纔會更新硬盤上的數據)。大於1的數字表明緩衝區的大小(單位是字節),-1(或者是任何負數)表明使用默認的緩衝區大小。

二、讀、寫文件

(1)讀寫字符

write和read方法分別表示寫、讀文件。

write方法會追加字符串到文件中已存在部分的後面。

read方法會按字符順序讀取文件。

f=open(r'D:\Python.txt','w')
f.write("hello")
f.write("world")
f.close()

f=open(r'D:\Python.txt','r')
print(f.read(1)) #h
print(f.read(3)) #ell

(2)讀寫行

writelines和readlines\readline能夠按行寫入或讀取文件

f=open(r'D:\Python.txt','w')
f.writelines("hello,susan\n")
f.writelines("hello,world\n")
f.writelines("hello,python\n")
f.close()

f=open(r'D:\Python.txt','r')
print(f.readline()) #hello,susan
#沒有f.writeline()方法,由於可使用write
print(f.readlines()) #['hello,world\n', 'hello,python\n']

(3)文件對象可迭代

文件對象是可迭代的,這意味着能夠直接在for循環中使用它們。

f=open(r'D:\Python.txt')
for line in f:
    print(line)  #每次讀取一行內容

三、關閉文件

若是想確保文件被關閉了,那麼應該使用try/finally語句,而且在finally子句中調用close方法

也可使用with語句;

with語句能夠打開文件而且將其賦值到變量上,以後就能夠將數據執行其餘操做。文件在語句結束後會被自動關閉,即便是因爲異常引發的結束也是如此。

#open file here
try:
    #write data to file
finally:
    file.close()


with open(r'D:\Python.txt','r') as f:
    print(f.readline()) #hello,world

 

本文內容摘自《Python基礎教程》一書

相關文章
相關標籤/搜索