python--ファイルとIO操作

1929 ワード

ファイルアクション
ファイル入出力
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
    ","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)