Python基礎知識之5

2021-10-01 05:08:22 字數 2284 閱讀 8569

1.檔案的開啟與關閉

# 新建乙個檔案,檔名為:test.txt

f =open

('test.txt'

,'w'

)# 關閉這個檔案

f.close(

)

2.檔案的讀寫

2.1 寫資料(write)

示例如下:

f =

open

('test.txt'

,'w'

)f.write(

'hello world, i am here!'

)f.close(

)

2.2讀資料(read)

使用read(num)可以從檔案中讀取資料,num表示要從檔案中讀取的資料的長度(單位是位元組),如果沒有傳入num,那麼就表示讀取檔案中所有的資料.

示例如下:

f =

open

('test.txt'

,'r'

)content = f.read(5)

print

(content)

print

("-"*30

)content = f.read(

)print

(content)

f.close(

)

readlines可以按照行的方式把整個檔案中的內容進行一次性讀取,並且返回的是乙個列表,其中每一行的資料為乙個元素.

示例如下:

#coding=utf-8

f =open

('test.txt'

,'r'

)content = f.readlines(

)print

(type

(content))i=

1for temp in content:

print

("%d:%s"

%(i, temp)

) i+=

1f.close(

)

readline每次讀取檔案中的一行資料

示例如下:

#coding=utf-8

f =open

('test.txt'

,'r'

)content = f.readline(

)print

("1:%s"

%content)

content = f.readline(

)print

("2:%s"

%content)

f.close(

)

2.3定位讀寫

示例如下:

#demo:把位置設定為:離檔案末尾,3位元組處

# 開啟乙個已經存在的檔案

f =open

("test.txt"

,"r"

)# 查詢當前位置

position = f.tell(

)print

"當前檔案位置 : "

, position

# 重新設定位置

f.seek(-3

,2)# 讀取到的資料為:檔案最後3個位元組資料

str= f.read(

)print

"讀取的資料是 : "

,str

f.close(

)

建立資料夾
import os

os.mkdir(

"張三"

)

獲取當前目錄
import os

os.getcwd(

)

改變預設目錄
import os

os.chdir(

"../"

)

獲取目錄列表
import os

os.listdir(

"../"

)

刪除資料夾
import os

os.rmdir(

"張三"

)

Python 基礎知識之總結(5)

第五天學習,複習前四天的知識點,並在原有知識點基礎上,引入新的內容。1.變數賦值,切記,變數命名不可以關鍵字命名 a 10 b hello world c a b c d d 2 10,20 2.資料型別,可通過type 來獲取變數的型別 2.1 數字 a1 10 整型 b1 1.2 浮點型 c1,...

5,Python函式基礎知識

函式的引數與返回值 lambda表示式 在python中,一切都是物件,函式 function 也不例外。函式其實就是一台機器,能夠把我們放進去的材料轉化成想要的物品。其實我們對函式並不陌生。我們平時用到的print input 等後面帶括號的語句都是函式。python中除了內建函式和庫函式之外,還...

python基礎知識之集合

鑑於前面已經對列表的一些用法進行過介紹,本篇文章就從元組開始說 首先,元組和列表的形式上是差不多的,都是儲存大量資料的一組集合,但是也是有不同點的 下面舉個列子 元組 test 1,3,xx 列表 test1 1,2,xx 從上面的列子可以看出在定義元組和列表時需要注意的不同,元組用的小括號,而列表...