今天继续整理原来写的 python 代码,下面是获取文件信息的 python 处理代码。

  获取指定目录下文件的文件名以及文件的数量,然后列出其中还存在的目录名称:

#!/usr/bin/env python2
#-*-encoding:utf-8-*-

import os,sys
def listdir(dir,file):
file.write(dir +'\n')
fielnum =0
list = os.listdir(dir)#列出目录下的所有文件和目录
for line in list:
filepath = os.path.join(dir,line)
if os.path.isdir(filepath):#如果filepath是目录,则再列出该目录下的所有文件
myfile.write(' '+ line +'//'+'\n')
for li in os.listdir(filepath):
myfile.write(' '+li +'\n')
fielnum = fielnum +1
elif os.path:#如果filepath是文件,直接列出文件名
myfile.write(' '+line +'\n')
fielnum = fielnum +1
myfile.write('all the file num is '+ str(fielnum))
dir = raw_input('please input the path:')
myfile = open('list.txt','w')
listdir(dir,myfile)
myfile.close()

  获取的文件名、目录信息会在当前路径下生成 list.txt 的文件。文件内容如下:

G:\codes\python\file_info
list.txt
list2.txt
list_filenames.py
list_filenames2.py
list_files+.py
test//
g.txt
mmm.pptx
test2//
list.txt
test3
all the file num is9

 
  下面是上面程序的升级版本,遍历了当前目录下的文件夹,继续执行遍历文件名的命令。

#!/usr/bin/env python2
#-*-encoding:utf-8-*-

"""os.walk(path),遍历path,返回一个对象,
他的每个部分都是一个三元组,
('目录x',[目录x下的目录list],目录x下面的文件)"""

import os
def walk_dir(dir,fileinfo,topdown=True):
for root, dirs, files in os.walk(dir, topdown):
for name in files:
print(os.path.join(name))
fileinfo.write(os.path.join(root,name)+'\n')
for name in dirs:
print(os.path.join(name))
fileinfo.write(' '+ os.path.join(root,name)+'\n')
dir = raw_input('please input the path:')
dir = r'G:\codes\python\file_info'
fileinfo = open('list2.txt','w')
walk_dir(dir,fileinfo)
fileinfo.close()

  shell 打印出来的结果是:

>>>================================ RESTART ================================
>>>
please input the path:G:\codes\python\file_info
list.txt
list2.txt
list_filenames.py
list_filenames2.py
list_files+.py
test
test2
g.txt
mmm.pptx
list.txt
test3
234.txt

  执行文件目录中 list2.txt 中的内容是:

G:\codes\python\file_info\list.txt
G:\codes\python\file_info\list2.txt
G:\codes\python\file_info\list_filenames.py
G:\codes\python\file_info\list_filenames2.py
G:\codes\python\file_info\list_files+.py
G:\codes\python\file_info\test
G:\codes\python\file_info\test2
G:\codes\python\file_info\test\g.txt
G:\codes\python\file_info\test\mmm.pptx
G:\codes\python\file_info\test2\list.txt
G:\codes\python\file_info\test2\test3
G:\codes\python\file_info\test2\test3\234.txt

  是目录的地方行首空了一定的位置。
 
  下面是另外一个增强版本,主要实现了遍历给定目录下所有文件,并计算所有文件的 MD5 值,然后将文件 MD5 值和文件名保存在目录下的 list3.txt 文件中,代码如下:

#!/usr/bin/env python2
#-*-encoding:utf-8-*-

import os
import sys
import md5

def walk_dir(dir,fileinfo,topdown=True):
    for root, dirs, files in os.walk(dir, topdown):
        for name in files:
            path = os.path.join(root,name)
            md5v = sumfile(path)
            newpath = path.replace(dir,'')
            fileinfo.write(newpath + ':' + md5v + '\n')

def sumfile(fpath):
    m = md5.new()
    fobj = open(fpath)
    while True:
        d = fobj.read(8096)
        if not d:
            break
        m.update(d)
    return m.hexdigest()

#获取脚本文件的当前路径
def cur_file_dir():
    #获取脚本路径
    path = sys.path[0]
    #判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)
#打印结果
print cur_file_dir()

def main():    #dir = raw_input('please input the path:')    dir = cur_file_dir()    fileinfo = open('list3.txt','w')    walk_dir(dir,fileinfo)if __name__ == '__main__':    main()

  运行后 list3.txt 文件中的内容如下:

\list.txt:0a732356981d24beab0d0c1c4092b2a7
\list2.txt:6cebc24b3a996be27c732557a2ce545f
\list3.txt:d41d8cd98f00b204e9800998ecf8427e
\list_filenames.py:9201c1eefcaf2fd04478cc2b6430c678
\list_filenames2.py:ca3f74bdb0a5485dd5d95d77da80141b
\list_files+.py:720d569d2f07f0c80e0d695db31749ab
\test\g.txt:d41d8cd98f00b204e9800998ecf8427e
\test\mmm.pptx:6f0e81ad84c22838337f0f619080e7f2
\test2\list.txt:d41d8cd98f00b204e9800998ecf8427e
\test2\test3\234.txt:d41d8cd98f00b204e9800998ecf8427e

  欢迎转载,请注明原文地址:http://vipscu.blog.163.com/blog/static/181808372201221121244906/

python 获取当前目录下文件(转)的更多相关文章

  1. python 获取当前目录下的文件目录和文件名

    python 获取当前目录下的文件目录和文件名   os模块下有两个函数: os.walk() os.listdir() 1 # -*- coding: utf-8 -*- 2 3 import os ...

  2. python获取目录下文件夹名称

    path = '/opt' dirs = os.listdir(path) for dir in dirs: print dir

  3. python 运行当前目录下的所有文件

     查看当前目录下所有py文件(本身除外run) import os file_list = os.listdir(os.getcwd()) # 获取当前目录下所有的文件名print(file_list ...

  4. python生成器 获取 目录下文件

    # os.walk()和os.list 都是得到所有文件的列表, 如果目录下文件特别多, 上亿了, 我们就需要生成器的方式获取 # 要求目录下面没有目录, 会递归到子目录下面找文件, (如果有子目录可 ...

  5. Python获取当前路径下的配置文件

    Python获取当前路径下的配置文件 有的时候想读取当前目录下的一个配置文件.其采用的办法是: import os # 获取当前路径 curr_dir = os.path.dirname(os.pat ...

  6. File获取当前目录下的所有子项 listFiles()

    package seday03; import java.io.File; /** * 获取一个目录中的所有子项 * @author xingsir */public class ListFilesD ...

  7. spring java 获取webapp下文件路径

    spring java 获取webapp下文件路径 @RequestMapping("/act/worldcup_schedule_time/imgdownload") @Resp ...

  8. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

  9. springboot打成jar后获取classpath下文件失败

    原文链接:https://blog.csdn.net/qq_18748427/article/details/78606432 springboot打成jar后获取classpath下文件失败 使用如 ...

随机推荐

  1. dreamweaver快捷键

    ---恢复内容开始--- 件菜单 新建文档 Ctrl+N 打开一个 HTML文件 Ctrl+O或者将文件从[文件管理器]或[站点]窗口拖动到[文档]窗口中 在框架中打开 Ctrl+Shift+O 关闭 ...

  2. javascript之小积累-匿名函数表达式的最佳实践

    在写js的时候,还是经常会用的匿名函数表达式,比如 setTimeout(function() { console.log(110); }, 1000); 上面那个function()就是匿名函数表达 ...

  3. git 较基础命令

    还需要进一步了解git的组织形式: git clone *.git 下载下来以git方式管理 如果直接下载压缩包做不到 git branch 分支相关命令 git checkout 可以换分支 git ...

  4. 2014嘉杰信息杯ACM/ICPC湖南程序设计邀请赛暨第六届湘潭市程序设计竞赛

    比赛链接: http://202.197.224.59/OnlineJudge2/index.php/Contest/problems/contest_id/36 题目来源: 2014嘉杰信息杯ACM ...

  5. 必须掌握的八个cmd 命令

    一,ping 它是用来检查网络是否通畅或者网络连接速度的命令.作为一个生活在网络上的管理员或者黑客来说,ping命令是第一个必须掌握的DOS命令,它 所利用的原理是这样的:网络上的机器都有唯一确定的I ...

  6. 一个文件夹可以link 到另外一个文件夹

    Creates a symbolic link. MKLINK [[/D] | [/H] | [/J]] Link Target /D      Creates a directory symboli ...

  7. Python2.7.12开发环境构建(自动补全)

    一.安装readline-devel包 Python的编译安装依赖于这个包 yum -y install readline-devel 二.安装Python2.7.12 Python官方网站(到此处下 ...

  8. hiho一下18周 RMQ问题再临

    RMQ问题再临 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 终于,小Hi和小Ho踏上了回国的旅程.在飞机上,望着采购来的特产--小Hi陷入了沉思:还记得在上上周他们去 ...

  9. MyEclipse优化-六步攻略

    1.首先是jsp的可视化页面 windows -> preferences->General-> Editors -> File Associations  在上方框内选择*. ...

  10. 缓存,socket乱码等

    在服务端默认的编码情况下,JAVA的SOCKET接收需要GBK编码,而C#的接收需要UTF-8编码