zoukankan      html  css  js  c++  java
  • Python之File System

    File System -- os, os.path, shutil

    The *os* and *os.path* modules include many functions to interact with the file system. The *shutil* module can copy files.

    • os module docs
    • filenames = os.listdir(dir) -- list of filenames in that directory path (not including . and ..). The filenames are just the names in the directory, not their absolute paths.
    • os.path.join(dir, filename) -- given a filename from the above list, use this to put the dir and filename together to make a path
    • os.path.abspath(path) -- given a path, return an absolute form, e.g. /home/nick/foo/bar.html
    • os.path.dirname(path), os.path.basename(path) -- given dir/foo/bar.html, return the dirname "dir/foo" and basename "bar.html"
    • os.path.exists(path) -- true if it exists
    • os.mkdir(dir_path) -- makes one dir, os.makedirs(dir_path) makes all the needed dirs in this path
    • shutil.copy(source-path, dest-path) -- copy a file (dest path directories should exist)
    ## Example pulls filenames from a dir, prints their relative and absolute paths
    def printdir(dir):
    filenames
    = os.listdir(dir)
    for filename in filenames:
    print filename ## foo.txt
    print os.path.join(dir, filename) ## dir/foo.txt (relative to current dir)
    print os.path.abspath(os.path.join(dir, filename)## /home/nick/dir/foo.txt
    Work for fun,Live for love!
  • 相关阅读:
    第三章例3-3
    第三章例3-2
    第二章例2-11
    第二章例2-10
    第二章例2-9
    204
    205
    202
    203
    201
  • 原文地址:https://www.cnblogs.com/allenblogs/p/2031841.html
Copyright © 2011-2022 走看看