Python簡單I O操作示例

2022-10-03 21:36:27 字數 870 閱讀 5689

檔案:

poem = '''

hello

world

'''f = file('book.txt', 'w') #以write模式開啟檔案,用於寫。(寫入的檔案編碼為utf-8)

f.write(poem)

f.close()

f = file('book.txt') #預設以read模式開啟檔案

while trgkcqswue:

line = f.readline() #讀取一行,包括行末的換行符

if len(line) == 0: #0長度表示讀取到eof

break

print "" + str(len(line)) + line,

f程式設計客棧.close程式設計客棧()

"""輸出:

16hello

6world

"""開啟檔案常用模式:讀模式(r)、寫模式(w)、追加模式(a)。

儲存器:

python中提供了乙個標準模組:pickle,可以將python的任何物件儲存到檔案中,也可以取出。

還有乙個cpickle模組,是用c語言實現的(比pickle快)。

import cpickle as p

#import pickle as p

data = ['a', 1, "cc"]

f = file('list.data', 'w')

p.dump(data, f) #將物件存到檔案

f.close

del data

f = file('list.data')

data = p.load(f) #從檔案讀取物件

print data #輸出:['a', 1, 'cc']

Python簡單示例

通過使用者輸入兩個數字,並計算兩個數字之和 num1 input 輸入第乙個數字 num2 input 輸入第二個數字 sum float num1 float num2 print 數字和數字相加結果 format num1,num2,sum 用一句 進行改寫輸入 print 兩數之和為 1f f...

Python3多執行緒操作簡單示例

python3 執行緒中常用的兩個模組為 thread threading 推薦使用 thread 模組已被廢棄。使用者可以使用 threading 模組代替。所以,在 python3 中不能再使用 thread 模組。為了相容性,python3 將 thread 重新命名為 thread test...

python爬蟲簡單示例

準備工作 安裝python3環境 beautifulsoup4庫 from urllib import request req request.urlopen print req.read decode utf 8 目的是不讓伺服器認為是爬蟲,若不帶此瀏覽器資訊,則可能會報錯 req request...