iT邦幫忙

2021 iThome 鐵人賽

DAY 7
1
自我挑戰組

Python 30天自我挑戰系列 第 7

Day07 - Python基本語法 Part 4,模組、檔案處理與多執行緒

範例程式主要來自於W3Schools

模組

  • 建立模組:新增一個.py檔,使用欲使用的模組名稱命名(這邊命名為mymodule.py),程式內包含以下函式。
def greeting(name):
  print("Hello, " + name)
  • 使用模組:在程式開頭import該模組(名稱同模組的檔案名稱),即可使用此模組中的函示。
# 使用mymodule模組並取名為mx
import mymodule as mx

mymodule.greeting("Jonathan")
  • 列出模組內所有可使用的函式與變數
import math
print(dir(math))
  • 只引用模組內的某一個函式
from math import sqrt
print(sqrt(64))

PIP

PIP是Python的套件管理器,讓我們可以很簡單的下載我們所需要的套件或模組。

  • 列出目前已安裝的套件
pip list
  • 下載套件
pip install [套件名稱]

https://ithelp.ithome.com.tw/upload/images/20210919/20141886hE2akXxuc6.png

  • 移除套件
pip uninstall [套件名稱]

檔案處理

  • 檔案開啟
myfile = open("檔案名稱","模式")
模式 說明
"r" 唯讀,若檔案不存在會回傳錯誤
"a" 附加,開啟檔案並在檔案最末尾寫入資料,若檔案不存在會自動建立檔案
"w" 寫入,開啟檔案以寫入資料,並覆蓋舊資料,若檔案不存在會自動建立檔案
"x" 建立,建立檔案,若檔案已存在會回傳錯誤

除了以上四種模式外,另外有兩種修飾詞用來指定檔案以何種格式開啟:

修飾詞 說明
"t" Text mode
"b" binary mode
  • 檔案讀取
  1. 讀取完整檔案:file.read()
  2. 讀取n個字元:file.read(n)
  3. 一次讀取一行:file.readline()

範例:建立一個文字檔 filesample.txt,其中內容如下:

Line 1: Good morning.
Line 2: Good afternoon.
Line 3: Good night.

情境一:讀取完整檔案

myfile = open("f:\\filesample.txt","r")

print(myfile.read())

https://ithelp.ithome.com.tw/upload/images/20210919/20141886UxO90hbAY9.png

情境二:讀取n個字元

myfile = open("f:\\filesample.txt","r")

# 讀取從最前面的10個字元
print(myfile.read(10))

# 接續之前的位置,繼續向後讀取5個字元
print(myfile.read(5))

https://ithelp.ithome.com.tw/upload/images/20210919/20141886avzpNE2h3a.png

情境三:一次讀取一行

myfile = open("f:\\filesample.txt","r")

# 讀取一行,印出
print(myfile.readline())

# 讀取一行,不印出
myfile.readline()

# 讀取一行,印出
print(myfile.readline())

https://ithelp.ithome.com.tw/upload/images/20210919/20141886jbGEd5rQ9Y.png

情境四:使用迴圈方式讀取檔案

myfile = open("f:\\filesample.txt","r")

# 使用迴圈的方式讀取檔案,每一個迴圈會一次讀取一行
for i in myfile:
  print(i)
  • 檔案寫入
    根據open的模式決定寫入方法。
    語法:file.write(內容)

  • 檔案關閉
    語法:file.close()

多執行緒處理

需使用threading模組。

  • 建立執行緒
mythread = threading.Thread(target=[function], args=())
# target:該執行緒要執行的物件
# args:給target調用的引數,Tuple型態
# 註:還有許多引數可使用,未來有需要再研究

注意,args需使用Tuple型態,如果物件本身只有一個引數:

# 錯誤寫法
args=(arg1)

# 正確寫法
args=(arg1,)
  • 執行緒開始
mythread.start()
  • 等待該執行緒結束
mythread.join()

範例:

import threading
import time

def mytask(x):
   for i in range(3):
    msg = "Thread {} is running. Count: {}"
    print(msg.format(x, i))
    time.sleep(1)

# 使用list儲存執行緒
threadlist = []

# 執行緒開始
for i in range(4):
  threadlist.append(threading.Thread(target=mytask, args =(i,)))
  threadlist[i].start()

# 等待執行緒結束
for i in range(4):
  threadlist[i].join()
  msg = "Thread {} is completed."
  print(msg.format(i))

print ("Total complete")

https://ithelp.ithome.com.tw/upload/images/20210919/201418863O1QBp9yL5.png

值得注意的一點是,建立執行緒時,物件需要的引數必須使用args導入,不可一起放在target。

錯誤範例:

import threading
import time

def mytask(x):
   for i in range(3):
    msg = "Thread {} is running. Count: {}"
    print(msg.format(x, i))
    time.sleep(1)

# 使用list儲存執行緒
threadlist = []

# 執行緒開始
for i in range(4):
  threadlist.append(threading.Thread(target = mytask(i))) # *** 錯誤範例 ***
  threadlist[i].start()

# 等待執行緒結束
for i in range(4):
  threadlist[i].join()
  msg = "Thread {} is completed."
  print(msg.format(i))

print ("Total complete")

最後產出結果會跟單執行緒相同,但目前還不太知道該如何解釋這個原因,只能先把此錯誤情境記錄下來:
https://ithelp.ithome.com.tw/upload/images/20210919/20141886CEkcy4GrjZ.png


上一篇
Day06 - Python基本語法 Part 3,函式與類別
下一篇
Day08 - Python虛擬環境
系列文
Python 30天自我挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言