temporary_directory_example.py
· 455 B · Python
Eredeti
import tempfile
import os
with tempfile.TemporaryDirectory() as temp_dir:
pid = os.getpid() # 取得當前進程 ID
temp_file = os.path.join(temp_dir, f"process_{pid}.txt")
# 建立並寫入臨時檔案
with open(temp_file, "w") as f:
f.write(f"這是進程 {pid} 的臨時檔案")
print(f"臨時目錄: {temp_dir}")
print(f"臨時檔案: {temp_file}")
# 離開 `with` 區塊後,臨時目錄和檔案將自動刪除
| 1 | import tempfile |
| 2 | import os |
| 3 | |
| 4 | with tempfile.TemporaryDirectory() as temp_dir: |
| 5 | pid = os.getpid() # 取得當前進程 ID |
| 6 | temp_file = os.path.join(temp_dir, f"process_{pid}.txt") |
| 7 | |
| 8 | # 建立並寫入臨時檔案 |
| 9 | with open(temp_file, "w") as f: |
| 10 | f.write(f"這是進程 {pid} 的臨時檔案") |
| 11 | |
| 12 | print(f"臨時目錄: {temp_dir}") |
| 13 | print(f"臨時檔案: {temp_file}") |
| 14 | |
| 15 | # 離開 `with` 區塊後,臨時目錄和檔案將自動刪除 |
| 16 |
temporary_file_example.py
· 316 B · Python
Eredeti
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
print(f"建立的臨時檔案: {temp_file.name}")
temp_file.write(b"這是一個具名的臨時檔案。\n")
# `delete=False` 允許我們在 `with` 區塊外存取該檔案
print("檔案仍然存在,可用於後續操作。")
| 1 | import tempfile |
| 2 | |
| 3 | with tempfile.NamedTemporaryFile(delete=False) as temp_file: |
| 4 | print(f"建立的臨時檔案: {temp_file.name}") |
| 5 | temp_file.write(b"這是一個具名的臨時檔案。\n") |
| 6 | |
| 7 | # `delete=False` 允許我們在 `with` 區塊外存取該檔案 |
| 8 | print("檔案仍然存在,可用於後續操作。") |
| 9 |
temporary_file_usage.py
· 282 B · Python
Eredeti
import tempfile
with tempfile.TemporaryFile(mode="w+t") as temp_file:
temp_file.write("這是一個臨時檔案。\n")
temp_file.seek(0) # 重置讀取位置
print("讀取臨時檔案內容:", temp_file.read())
# 離開 `with` 區塊後,臨時檔案將自動刪除
| 1 | import tempfile |
| 2 | |
| 3 | with tempfile.TemporaryFile(mode="w+t") as temp_file: |
| 4 | temp_file.write("這是一個臨時檔案。\n") |
| 5 | temp_file.seek(0) # 重置讀取位置 |
| 6 | print("讀取臨時檔案內容:", temp_file.read()) |
| 7 | |
| 8 | # 離開 `with` 區塊後,臨時檔案將自動刪除 |
| 9 |