python 扫描目录下所有文件并读取文件

先介绍两个函数:

一。os.walk()可以得到一个三元tupple(dirpath,sub_dirs, filenames),其中第一个为起始路径,第二个为起始路径下的所有文件夹,第三个是起始路径下的所有文件。
其中dirpath是一个string,代表目录的路径,sub_dirs是一个list,包含了dirpath下所有子目录的名字。filenames是一个list,包含了非目录文件的名字。这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name).

二。withopen(spcial_file_dir)assource_file

with 语句是在 Python 2.5 版本引入的,从 2.6 版本开始成为缺省的功能。

with 语句作为 try/finally 编码范式的一种替代,用于对资源访问进行控制的场合。

 

如果要打开文件并保证最后关闭他,只需要这么做:

 

withopen("x.txt") as f:
    data=f.read()
    do something with data

 

with-as表达式极大的简化了每次写finally的工作,无需自己手动将打开文件close()掉

若要更深理解:

http://zhoutall.com/archives/325

http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/

扫描目录读取文件,不考虑子目录情况

 

try:
    source_dir = '/dir/source/'
    target_dir = '/dir/old/'
    for root, sub_dirs, files in os.walk(source_dir):
        for special_file in files:
            spcial_file_dir = os.path.join(root, special_file)
            # 打开文件的两种方式
            # 1.文件以绝对路径方式
            with open(spcial_file_dir) as source_file:
            # 2.文件以相对路径方式
            # with open(r'dir_test/test.txt') as source_file:
                for line in source_file:
                    # do something
            # 移动文件
            shutil.move(spcial_file_dir, target_dir)
            logger.info(u'文件%s移动成功'% spcial_file_dir)
    return HttpResponse(json.dumps({'result':0}))
except Exception as e:
    # do something

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值