Pin-Jiun / Python

Python Document
0 stars 0 forks source link

8-File Read and Write #8

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago
# 1. 檔案操作流程
# 1.1 開啟檔案、操作檔案、關閉檔案
# 1.2 開啟模式、檔案編碼 UTF-8
# 1.3 最佳實務:使用 with ... as ... 語法
# 1.4 檔案物件

# 2. 讀取檔案
# 2.1 一次讀取全部:read()
# 2.2 逐行讀取資料:使用 for 迴圈

# 3. 寫入檔案
# 3.1 寫入字串到檔案中:write(字串)
# 3.2 寫入換行符號:\n

# 4. 讀取、儲存 JSON 格式的資料
# 4.1 載入內建的 json 模組
# 4.2 讀取資料:json.load(檔案物件)
# 4.3 寫入資料:json.dump(資料, 檔案物件)

#檔案物件=open("檔案路徑",mode=r,w,r+)
a = open("data2.txt",mode="w")
a.write("PJL is very smart.\n")
a.write("I'm on board with it.\n")
a.close()       #一定要關閉檔案,才可有效釋放資源

#with為最務實的方法,會自動關閉檔案
with open("data.txt",mode="w",encoding="utf-8") as a:
    #如果是中文要加入encoding="utf-8"
    a.write("中文欸~~\n對阿!")

with open("data.txt",mode="r",encoding="utf-8") as file:
    data=file.read()    #全部讀取

print(data)

with open("data3.txt",mode="w",encoding="utf-8") as a:
    a.write("3\n5")

sum=0
with open("data3.txt",mode="r",encoding="utf-8") as file:
    #data=file.read()是全部讀取,不是很好用
    #一行一行的讀取 for 變數名稱 in 檔案物件
    for line in file:
        sum = sum + int(line)
    print(sum)  #8

import json

with open("config.json",mode="r") as file:
    data = json.load(file)
    #data為字典型態

print(data)
print("name: ",data["name"])
data["name"]=["New Name"]   #只更動到變數data中的資料,原本檔案data.txt是沒有更動的

with open("config.json",mode="w") as file:
    json.dump(data,file)    #把資料複寫回檔案data.txt

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist


The syntax is used to open multiple files

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()
Pin-Jiun commented 1 year ago

tkinter

可以用 tkinter 中的 tkinter.tkFileDialog() 打開選取檔案和目錄的視窗

askopenfilename()

打開可以選取檔案的視窗,並回傳檔案的路徑

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)

tkinter filedialog 判斷開啟檔案對話框回傳的檔案

通常程式會需要去判斷使用者是否選擇了一個合法的檔案或者是取消動作根本沒選檔案, 這邊示範最簡單的方法是接著判斷檔案是否為空,不為空的話才繼續做接下來的程式邏輯, filedialog.askopenfilename() 會回傳的類型為 str,若取消的話會回傳一個空的 tuple (),

tkinter filedialog 設定開啟檔案對話框的標題

filedialog 想要設定一些提示訊息在開啟檔案對話框的標題,來提示使用者到底要開什麼檔案的話, 可以在 filedialog.askopenfilename() 參數裡指定 title,

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(parent=root, 
                                    title='Select file')
Pin-Jiun commented 1 year ago

不同的作業系統對路徑的語法有不同的規定,在Linux與Mac OS中,採用斜線(/)符號來分隔目錄與子目錄,而在Windows中,則是使用反斜線(\)符號來分隔。此外,在Linux中只有單一的根目錄;而在Windows中,每一台磁碟機都是一個獨立的根目錄(例如:A:\ 、C:\ 、D:\等)。

如果想要讓所有作業系統中都能執行,在程式設計時就要處理這兩種狀況。

幸運的是,Python提供了相關函式以方便程式來指定檔案路徑,而不必擔心系統的差異。例如使用os.path.join()函式來處理,os.path.join()會返回檔案路徑的字串,而且會以系統正確的分隔符號來分割資料夾和檔名。可以在不同的作業系統中試試下面的程式碼:

import os
os.path.join('product','men','clothes')

os.path — 處理路徑名稱

os.path模組裡面有很多與檔案名稱和檔案的路徑有關的函式。因為os.path是os模組裡面的模組,只需要import os到py檔案裡面就可以使用了。我們可以使用os.path來取得路徑名稱。

如果要建立路徑的話,可以使用os.path.join()。記得我們在前面曾經提過os.path會依照目前正在使用的作業系統以系統正確的分隔符號來分割資料夾和檔名。無論是使用哪一個作業系統,os.path.join()都不會檢查參數是否合法。因此在使用時,最好是自己寫一個函式來檢查路徑的合法性。

os.path.join()

前面已經提過,os.path.join()會返回檔案路徑的字串,而且以系統正確的分隔符號來分隔資料夾與檔名。此外,如果想要為檔案建立字串的話,使用os.path.join()會相對方便:

files = ["index.html","main.css","main.js"]
for filename in files:
    print(os.path.join("new_project", filename))

我們可以用下面方式取得目前工作目錄下面的特定資料夾:下面程式碼可以取得目前工作目錄下面csv資料夾中的所有檔案名稱。

url = os.path.join(os.curdir,'csv')
os.listdir(url)

https://medium.com/seaniap/python-%E4%BD%BF%E7%94%A8%E6%AA%94%E6%A1%88%E7%B3%BB%E7%B5%B1-eaecbe7001dd

Pin-Jiun commented 1 year ago

Python pathlib 模組取得當前路徑的方法

這邊介紹 Python pathlib 模組取得當前路徑的方法,使用 pathlib.Path().absolute() 可以取得當前目錄的絕對路徑,程式碼如下,

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pathlib

print(pathlib.Path().absolute())