溫馨提示×

Linux使用Python如何管理文件系統

小樊
102
2024-11-30 20:03:52
欄目: 編程語言

在Linux中,你可以使用Python的內置庫osshutil來管理文件系統

  1. 創建目錄:
import os

directory_name = "new_directory"

# 檢查目錄是否已存在
if not os.path.exists(directory_name):
    os.makedirs(directory_name)
    print(f"{directory_name} created.")
else:
    print(f"{directory_name} already exists.")
  1. 刪除目錄:
import shutil

directory_name = "new_directory"

# 檢查目錄是否存在
if os.path.exists(directory_name):
    shutil.rmtree(directory_name)
    print(f"{directory_name} deleted.")
else:
    print(f"{directory_name} does not exist.")
  1. 復制文件:
import shutil

source_file = "source_file.txt"
destination_file = "destination_file.txt"

if os.path.exists(source_file):
    shutil.copy2(source_file, destination_file)
    print(f"{source_file} copied to {destination_file}.")
else:
    print(f"{source_file} does not exist.")
  1. 移動文件:
import os

source_file = "source_file.txt"
destination_file = "destination_file.txt"

if os.path.exists(source_file):
    os.rename(source_file, destination_file)
    print(f"{source_file} moved to {destination_file}.")
else:
    print(f"{source_file} does not exist.")
  1. 讀取文件內容:
with open("file.txt", "r") as file:
    content = file.read()
    print(content)
  1. 寫入文件內容:
file_name = "file.txt"
content = "Hello, World!"

with open(file_name, "w") as file:
    file.write(content)

這些示例展示了如何使用Python在Linux中管理文件系統的基本操作。你可以根據需要擴展這些示例以執行更復雜的文件操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女