iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 30
0
Google Developers Machine Learning

初心者的自我挑戰系列 第 30

完賽啦! Python basic 4

今天是鐵人賽最後一天,回頭看著這一個月覺得非常充實,每一天都有持續努力,也漸漸喜歡上紀錄所學的感覺,可以回頭看自己哪裡不足。我想之後也會繼續更新進度的。
那今天繼續學習python!補足自己不熟練的部分!

首先講解封包package意思:

#package 封包
#包含模組的資料夾:用來整理分類模組

#專案檔案配置
#-專案資料夾
   # -主程式main.py
   # -封包資料夾
     #   - __init__.py   #裡面留空即可,初始
     #   - 模組1.py
     #   - 模組2.py

#使用封包:
import 封包名稱.模組名稱 as 模組別名
#主程式
import geometry.point
result=geometry.point.distance(3,4)
print(result)

#主程式要放在封包外,跟封包同一層
#geometry為封包資料夾,內有__init__.py  line.py  point.py等等模組

文字檔案(txt)的讀取與儲存

#開啟檔案->讀取或寫入->關閉檔案

#檔案物件 = open(檔案路徑,mode=開啟模式)
#開啟模式 = (-r:讀取 -w:寫入 -r+:讀寫)

#讀取檔案
#檔案物件.read() #讀取全部文字
#for 變數 in 檔案物件:  依序讀取每行文字到變數中

#讀取jSON格式
#import json
#讀取到的資料 = json.load(檔案物件)

#寫入檔案
#檔案物件.write(字串)

#寫入json資料
#import json
#json.dump(要寫入的資料,檔案物件)

#關閉檔案,釋放資源

#最佳實務:
#with open(檔案路徑,mode=開啟模式) as 檔案物件:
#   讀取或寫入檔案的格式
#以上會自動關閉檔案


#EX:
file=open("data.txt" , mode="w")
file.write("hello")
file.close()

#EX2:中文
file = open('data2.txt' , mode='w', encoding='utf-8')
file.write("好")
file.close()

#EX3:最佳實務寫法
with open('data3.txt', mode='w', encoding='utf-8') as file:
    file.write("學習真好\n加油加油")

#EX4讀取檔案

with open('data.txt',mode='r',encoding="utf8") as file:
    data = file.read()
print(data)

#一行一行讀取資料做處理:

sum = 0 
with open('data4.txt', mode= "r") as file:
    for line in file: #一行一行讀取
        sum += int(line)  #讀出來是字串型態喔
print(sum)

類別class:

#class 類別
#封裝變數或函式,通稱為類別(class)的屬性(attributes)

#定義類別:
#class 類別名稱:
    #定義變數
    #定義函式

#EX:
class Test:
    x=3                #定義變數
    def say():         #定義函式
        print('Hello')

#使用類別屬性:
#類別名稱.屬性名稱

#EX2:
Test.x + 3
Test.say()

#EX3:
class IO:   #定義一個類別,有兩個屬性supportedSrcs 和 read
    supportedSrcs = ['console','file']
    def read(src):
        if src not in IO.supportedSrcs:
            print("Not supported")
        else:
            print("read from",src)

print(IO.supportedSrcs)
IO.read('file')
IO.read('internet')

上一篇
Python Basic 3
系列文
初心者的自我挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言