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

转载于:https://www.cnblogs.com/allenblogs/archive/2011/04/28/2031841.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值