天天看點

Python檔案操作

 ​

[1.os]

1.重命名:os.rename(old, new)

2.删除:os.remove(file)

3.列出目錄下的檔案 :os.listdir(path)

4.擷取目前工作目錄:os.getcwd()

5.改變工作目錄:os.chdir(newdir)

6.建立多級目錄:os.makedirs(r"c:/python /test")

7.建立單個目錄:os.mkdir("test")

8.删除多個目錄:os.removedirs(r"c:/python") #删除所給路徑最後一個目錄下所有空目錄。

9.删除單個目錄:os.rmdir("test")

10.擷取檔案屬性:os.stat(file)

11.修改檔案權限與時間戳:os.chmod(file)

12.執行作業系統 指令:os.system("dir")

13.啟動新程序:os.exec(), os.execvp()

14.在背景執行程式:osspawnv()

15.終止目前程序:os.exit(), os._exit()

16.分離檔案名:os.path.split(r"c:/python/hello.py") --> ("c://python", "hello.py")

17.分離擴充名:os.path.splitext(r"c:/python/hello.py") --> ("c://python//hello", ".py")

18.擷取路徑名:os.path.dirname(r"c:/python/hello.py") --> "c://python"

19.擷取檔案名:os.path.basename(r"r:/python/hello.py") --> "hello.py"

20.判斷檔案是否存在:os.path.exists(r"c:/python/hello.py") --> True

21.判斷是否是絕對路徑:os.path.isabs(r"./python/") --> False

22.判斷是否是目錄:os.path.isdir(r"c:/python") --> True

23.判斷是否是檔案:os.path.isfile(r"c:/python/hello.py") --> True

24.判斷是否是連結檔案:os.path.islink(r"c:/python/hello.py") --> False

25.擷取檔案大小:os.path.getsize(filename)

26.*******:os.ismount("c://") --> True

27.搜尋目錄下的所有檔案:os.path.walk()

[2.shutil]

1.複制單個檔案:shultil.copy(oldfile, newfle)

2.複制整個目錄樹:shultil.copytree(r"./setup", r"./backup")

3.删除整個目錄樹:shultil.rmtree(r"./backup")

[3.tempfile]

1.建立一個唯一的臨時檔案:tempfile.mktemp() --> filename

2.打開臨時檔案:tempfile.TemporaryFile()

[4.StringIO] #cStringIO是StringIO子產品的快速實作子產品

1.建立記憶體 檔案并寫入初始資料 :f = StringIO.StringIO("Hello world!")

2.讀入記憶體檔案資料:print f.read() #或print f.getvalue() --> Hello world!

3.想記憶體檔案寫入資料:f.write("Good day!")

4.關閉記憶體檔案:f.close()

[5.glob]

1.比對檔案:glob.glob(r"c:/python/*.py")