Python中的os模塊:操作文件和目錄的利器

在Python開發中,經常需要操作文件和目錄。此時,就需要使用Python中的os模塊。os模塊提供了一系列與操作系統交互的函數,可實現文件和目錄的創建、複製、刪除、重命名、遍歷等功能。本文將從多個方面介紹os模塊的使用。

一、獲取當前工作目錄


import os
current_dir = os.getcwd()
print("當前工作目錄:", current_dir)

os.getcwd()函數可以獲取當前工作目錄。輸出結果如下:

當前工作目錄:/Users/user_name

二、創建和刪除目錄

os.mkdir()函數可以創建目錄,os.rmdir()函數可以刪除目錄。


import os
# 創建目錄
os.mkdir("testdir")
# 判斷目錄是否存在
if os.path.exists("testdir"):
    print("testdir目錄存在")
# 刪除目錄
os.rmdir("testdir")
# 判斷目錄是否存在
if not os.path.exists("testdir"):
    print("testdir目錄不存在")

輸出結果如下:

testdir目錄存在
testdir目錄不存在

三、遍歷目錄

os.walk()函數可以遍歷目錄及其子目錄中的所有文件和子目錄。


import os
# 遍歷目錄
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

輸出結果如下:

./subdir/file1.txt
./subdir/subsubdir/file3.txt
./subdir/subsubdir
./subdir/file2.txt
./subdir
./file4.txt
./file3.txt
./file2.txt
./file1.txt
.

四、文件操作

1. 文件讀寫

os模塊提供了兩種讀寫文件的方式:使用open函數和使用os.fdopen函數。

使用open函數:


import os
# 寫文件
with open("file.txt", "w") as f:
    f.write("hello, world!")
# 讀文件
with open("file.txt", "r") as f:
    print(f.read())

使用os.fdopen函數:


import os
# 寫文件
fd = os.open("file.txt", os.O_WRONLY|os.O_CREAT)
with os.fdopen(fd, "w") as f:
    f.write("hello, world!")
# 讀文件
fd = os.open("file.txt", os.O_RDONLY)
with os.fdopen(fd, "r") as f:
    print(f.read())

2. 文件重命名和刪除

os.rename()函數可以重命名文件,os.remove()函數可以刪除文件。


import os
# 重命名文件
os.rename("file.txt", "new_file.txt")
# 判斷文件是否存在
if os.path.exists("new_file.txt"):
    print("new_file.txt文件存在")
# 刪除文件
os.remove("new_file.txt")
# 判斷文件是否存在
if not os.path.exists("new_file.txt"):
    print("new_file.txt文件不存在")

輸出結果如下:

new_file.txt文件存在
new_file.txt文件不存在

五、總結

os模塊是Python中非常實用的一個模塊,可以實現對文件和目錄的操作。本文主要介紹了os模塊的多個方面,包括獲取當前工作目錄、創建和刪除目錄、遍歷目錄、文件讀寫、文件重命名和刪除等。在實際開發中,不同的場景需要使用不同的函數來滿足需求。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/181660.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-23 06:44
下一篇 2024-11-23 06:44

相關推薦

發表回復

登錄後才能評論