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

来源:互联网 发布:火焰之地怎么去乎门人 编辑:程序博客网 时间:2024/06/07 05:21

先介绍两个函数:

一。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


1 0
原创粉丝点击