1. 程式人生 > >python -- 檔案和IO操作

python -- 檔案和IO操作

檔案操作

檔案輸入輸出

open(filename, mode)

  • ### filename 是該檔案的字串名;
  • ### mode 是指明檔案型別和操作的字串。

mode 的第一個字母表明對其的操作。

  • ### ‘r’ open for reading (default)
  • ### ‘w’ open for writing, truncating the file first
  • ### ‘x’ create a new file and open it for writing
  • ### ‘a’ open for writing, appending to the end of the file if it exists
  • ### ‘b’ binary mode
  • ### ‘t’ text mode (default)
  • ### ‘+’ open a disk file for updating (reading and writing)
#r表示原始的,不解析字串中的轉義內容
f = open(r"c:\readme.txt", "a")
f.writelines(["aa","\r\n","bb"])
f.close()

#使用with之後,不需要close()檔案
with open(r"d:\readme.txt", "r") as f:
    for line in f:
        print(line.strip())

操作檔案和目錄

import os
print(os.path.abspath(".")) #c:\train
newpath = os.path.join(os.path.abspath("."), "dir1")    #新目錄名稱dir
os.mkdir(newpath)#建立目錄
#刪除目錄
os.rmdir(r"c:\train\dir1")

os.path處理路徑

os.path.split(/Users/joe/Desktop/testdir)
os.path.splitext()#可以直接得到副檔名.
#使用rename()對檔案重新命名和remove()刪掉檔案.
#利用Python的特性來過濾檔案。比如我們要列出當前目錄下的所有目錄,只需要一行程式碼:
[x for
x in os.listdir('.') if os.path.isdir(x)] #['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...] #要列出所有的.py檔案,也只需一行程式碼: [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'] #['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py'] l1 = [path for path in os.listdir(".") if os.path.isdir(path)==False] for path in l1: print(path)