2023年6月13日 星期二

[Python] 檔案的新增、刪除、更名

需求模組

import os


新增檔案

# 指定檔案路徑
file_path = 'path/to/file.txt'
# 建立空白檔案
open(file_path, 'w').close()
# 或者寫入內容到檔案中
with open(file_path, 'w') as file:
    file.write('這是檔案的內容。')

刪除檔案

# 指定要刪除的檔案路徑
file_path = 'path/to/file.txt'
# 使用os.remove()函數刪除檔案
os.remove(file_path)

更改檔案名稱

# 原始檔案名稱和路徑
old_file_path = 'path/to/old_file.txt'
# 新的檔案名稱和路徑
new_file_path = 'path/to/new_file.txt'
# 使用os.rename()函數進行更名
os.rename(old_file_path, new_file_path)

沒有留言:

張貼留言