溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python Linux文件系統(tǒng)操作進(jìn)階

發(fā)布時間:2024-09-11 21:52:41 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在Python中,我們可以使用osshutil庫來執(zhí)行Linux文件系統(tǒng)的操作

  1. 獲取當(dāng)前工作目錄:
import os

current_directory = os.getcwd()
print(current_directory)
  1. 創(chuàng)建一個新目錄:
import os

new_directory = "new_folder"
os.mkdir(new_directory)
  1. 創(chuàng)建多級目錄:
import os

os.makedirs("dir1/dir2/dir3")
  1. 重命名文件或目錄:
import os

os.rename("old_name", "new_name")
  1. 刪除文件:
import os

os.remove("file_name")
  1. 刪除目錄:
import os

os.rmdir("directory_name")
  1. 刪除多級目錄:
import shutil

shutil.rmtree("directory_name")
  1. 復(fù)制文件:
import shutil

shutil.copy("source_file", "destination_file")
  1. 復(fù)制目錄:
import shutil

shutil.copytree("source_directory", "destination_directory")
  1. 移動文件或目錄:
import shutil

shutil.move("source", "destination")
  1. 獲取文件或目錄的信息:
import os

# 獲取文件或目錄的大小
size = os.path.getsize("file_or_directory")

# 獲取文件或目錄的修改時間
modification_time = os.path.getmtime("file_or_directory")

# 獲取文件或目錄的訪問時間
access_time = os.path.getatime("file_or_directory")

# 獲取文件或目錄的創(chuàng)建時間
creation_time = os.path.getctime("file_or_directory")
  1. 判斷文件或目錄是否存在:
import os

if os.path.exists("file_or_directory"):
    print("File or directory exists.")
else:
    print("File or directory does not exist.")
  1. 判斷是否為文件:
import os

if os.path.isfile("file_name"):
    print("It's a file.")
else:
    print("It's not a file.")
  1. 判斷是否為目錄:
import os

if os.path.isdir("directory_name"):
    print("It's a directory.")
else:
    print("It's not a directory.")

這些操作只是Linux文件系統(tǒng)操作的基本示例。你可以根據(jù)需要組合這些操作來實現(xiàn)更復(fù)雜的功能。同時,你還可以使用glob庫來查找符合特定模式的文件和目錄。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI