python -- 文件和IO操作

文件操作

文件輸入輸出

open(filename, mode)

  • filename 是該文件的字符串名;

  • mode 是指明文件類型和操作的字符串。

mode 的第一個(gè)字母表明對(duì)其的操作。

  • '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表示原始的,不解析字符串中的轉(zhuǎn)義內(nèi)容
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)#創(chuàng)建目錄
#刪除目錄
os.rmdir(r"c:\train\dir1")

os.path處理路徑

os.path.split(/Users/joe/Desktop/testdir)
os.path.splitext()#可以直接得到文件擴(kuò)展名.
#使用rename()對(duì)文件重命名和remove()刪掉文件.
#利用Python的特性來過濾文件。比如我們要列出當(dāng)前目錄下的所有目錄,只需要一行代碼:
[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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容