Python入門系列(八)

2021-09-24 03:55:34 字數 1055 閱讀 5195

python讀取檔案

首先,我們新建乙個叫做ex15_sample.txt的txt檔案:檔案內容如下:

i want to open this file and read it
在使用ar**函式之前,我們先嘗試著讀取一下這個檔案試試,**如下:

>>> txt=open('ex15_sample.txt')

>>> txt.read()

讀取的內容如下:

'i want to open this file and read it '
我們改造一下這個例子,編寫乙個python指令碼,內容如下:

#coding=utf-8

from sys import ar**

script, filename = ar**

txt = open(filename)

print "我指令碼名字是 %r:" % filename

print "讀取的檔案內容是%r"%txt.read()

執行這段指令碼,我們得到的內容如下:

python testopenfile.py ex15_sample.txt
執行結果如下:

我指令碼名字是 'ex15_sample.txt':

讀取的檔案內容是'i want to open this file and read it '

this is a new file,we try read it again
再次執行指令碼testopenfile.py,我們替換一下檔名稱,**如下:

ps f:\phyton_project> python testopenfile.py ex16_sample.txt

我指令碼名字是 'ex16_sample.txt':

讀取的檔案內容是'this is a new file,we try read it again'

python3 7入門系列八 函式

函式是具有名字的一段可重複使用的 塊 定義函式使用關鍵字 def def hello print hello hello hello 函式的引數 def hello name print hello,name hello tom hello,tom 其中,定義hello函式時的引數name是形參,呼...

python 入門學習(八)

異常處理 python在遇到問題時會自動引發異常,也可以用raise故意引發異常,異常種類必須是已有的 raise ioerror this is a test.traceback most recent call last file line 1,in raise ioerror this is ...

Python入門系列(四)

今天我們分享一下python中的字串格式化,python的字串格式化,大致分為兩種 使用 對字串進行格式化 s 字串,格式化字串,並提供佔位符 name 張三 print 我的名字是 s name 我的名字是 張三為了方便擴充套件,我們把這個例子再次拓展一下,name 張三 age 30 score...