python--輸入輸出

print 2會打印2而後換行,若不想換行,能夠print 2,函數

格式化打印spa

a=2
b=3
format = 'a=%d, b=%d'
print format % (a,b)

輸入,raw_inputcode

a=raw_input('請輸入一個字符串:')
print '你輸入的是:',a

文件操做orm

f = open('123.txt','w')
f.write('hello world')

文件打開參數:blog

r  讀內存

w  寫字符串

a  追加input

b  二進制it

+form

默認是r.

open函數中的第三個參數爲緩衝. 默認爲0,無緩衝;正數表示緩衝區的大小; 負數表示使用默認的緩衝的大小. 當使用flush或close時才更新硬盤上的數據.

使用with打開文件,能夠在異常退出後也能關閉文件.

with open('123.txt') as f:
    do_someting(f)

f.read(n) #讀取n個直接.

f.read() #讀取所有內容

f.readline() #讀一行,最後會有一個\n

f.readlines #讀取所有行

f = open('123.txt')
while True:
    line = f.readline()
    if not line: 文件讀完
        break
    print line,
f.close()

當一次將文件讀入內存佔空間時,可使用fileinput模塊.

import fileinput
for line in fileinput .input('123.txt'):
    print line,

待續

相關文章
相關標籤/搜索