python基本寫法 python操作檔案常用寫法

2021-10-21 05:10:49 字數 1195 閱讀 8083

#p1 開啟檔案、讀檔案、關閉檔案的典型方法

try:

f=open('d:/test.txt','r')

print(f.read())

finally:

if f:

f.close()

#p2 推薦的簡潔寫法,不必顯示的關閉檔案描述符

#open返回的物件在python中稱作file-like 物件,可以是位元組流、網路流、自定義流等

with open('d:/test.txt','r') as f:

#按行讀取

#p4 可以指定編碼讀取相應的資料,還可以忽略非法編碼

with open('d:/test.txt','r',encoding='gbk',errors='ignore') as f3:

for line in f3.readlines():

print(line.strip())

#p5 寫檔案的流程和讀檔案是一樣的 ×××檔案、寫入內容、關閉檔案

# 'r'    open for reading (default)

# 'w'    open for writing, truncating the file first

# 'x'    open for exclusive creation, failing if the file already exists

# 'b'    binary mode

# 't'    text mode (default)

# '+'    open a disk file for updating (reading and writing)

# 'u'    universal newlines mode (deprecated)

with open('d:/test12.txt','a+') as f4:

for line in f4.readlines():

print(line.strip())

f4.write('a new line2!')

python中迭代器的基本方法 Python迭代器

迭代器是可以迭代的物件。在本教程中,您將了解迭代器的工作原理,以及如何使用 iter 和 next 方法構建自己的迭代器。迭代器在python中無處不在。它們優雅地實現在迴圈,推導,生成器等中,但隱藏在明顯的視覺中。python中的迭代器只是乙個可以迭代的物件。乙個將一次返回資料的物件或乙個元素。從...

CUDA C 基本寫法

我們來看看基本的cuda c 寫法 include cuda runtime.h include device launch parameters.h global void addkernel int dev p cuda的gpu計算操作,它讓gpu的執行緒分別對dev p陣列的每個元素並行地執行...

Ubuntu vim基本外掛程式配置 Python版

記錄本人簡單vim配置,防止以後重新配置時遺忘。將目錄中的 vimrc 移動到home目錄並重命名為 vimrc 將 vimrc 中的作者頭刪除 安裝vundle外掛程式管理 git clone vim bundle vundle.vim開啟vim,輸入下面指令安裝外掛程式 youcompletem...