Python操作文件夹

python对文件夹的操作汇总,方便查阅使用

1、遍历指定目录,显示目录下的所有文件名

#-*- coding:utf-8 -*-
import os
def fileInFolder(filepath):
    pathDir =  os.listdir(filepath)  # 获取filepath文件夹下的所有的文件
    files = []
    for allDir in pathDir:
        child = os.path.join(‘%s\\%s‘ % (filepath, allDir))
        files.append(child.decode(‘gbk‘))  # .decode(‘gbk‘)是解决中文显示乱码问题
        # print child
        # if os.path.isdir(child):
        #     print child
        #     simplepath = os.path.split(child)
        #     print simplepath
    return files

filepath = "C:\\files"
print  fileInFolder(filepath)

输出:
[u‘C:\\files\\a.txt‘, u‘C:\\files\\b.txt‘, u‘C:\\files\\c‘]

  

2、遍历文件夹及其子文件夹的所有文件,获取文件的列表

#-*- coding:utf-8 -*-
import os
def getfilelist(filepath):
    filelist =  os.listdir(filepath)  # 获取filepath文件夹下的所有的文件
    files = []
    for i in range(len(filelist)):
        child = os.path.join(‘%s\\%s‘ % (filepath, filelist[i]))
        if os.path.isdir(child):
            files.extend(getfilelist(child))
        else:
            files.append(child)
    return files
filepath = "C:\\files"
print getfilelist(filepath)

输出:
[‘C:\\files\\a.txt‘, ‘C:\\files\\b.txt‘, ‘C:\\files\\c\\d.txt‘, ‘C:\\files\\c\\e.txt‘, ‘C:\\files\\c\\f\\g.txt‘]

  

3、Python 遍历子文件和所有子文件夹 输出字符串

参考: http://blog.csdn.net/Qian_F/article/details/9896283

#-*- coding:utf-8 -*-
import os
def getfilelist(filepath, tabnum=1):
    simplepath = os.path.split(filepath)[1]
    returnstr = simplepath+"目录<>"+"\n"
    returndirstr = ""
    returnfilestr = ""
    filelist = os.listdir(filepath)
    for num in range(len(filelist)):
        filename=filelist[num]
        if os.path.isdir(filepath+"/"+filename):
            returndirstr += "\t"*tabnum+getfilelist(filepath+"/"+filename, tabnum+1)
        else:
            returnfilestr += "\t"*tabnum+filename+"\n"
    returnstr += returnfilestr+returndirstr
    return returnstr+"\t"*tabnum+"</>\n"

filepath = "C:\\files"
f = open("test.xml","w+")
f.writelines(getfilelist(filepath))
f.close()

  

4、对文件批量更名

#-*- coding:utf-8 -*-
import os
def filesRename(filepath):
    filelist =  os.listdir(filepath)  # 获取filepath文件夹下的所有的文件
    files = []
    for i in range(len(filelist)):
        child = os.path.join(‘%s\\%s‘ % (filepath, filelist[i]))
        if os.path.isdir(child):
            continue
        else:
            newName = os.path.join(‘%s\\%s‘ % (filepath, str(i) + "_" + filelist[i]))
            print newName
            os.rename(child, newName)
filepath = "C:\\files2"
filesRename(filepath)
时间: 2024-08-05 12:40:43

Python操作文件夹的相关文章

【Python】Python对文件夹的操作

上一篇介绍了Python对文件的读写操作,现在来介绍一下Python对文件夹的操作.由于我是项目中用到的,所以我就以我的实际应用实例来说明吧.希望对大家有所帮助. 1.实例需求: 现在有一个文件夹myDir,该文件夹中又有n个文件夹dir1,Dir2, ..., dirN,每个文件夹中又有m个文件,这个实例需要达到的目的就是要将这n个文件夹dir1,Dir2, ..., dirN中的所有文件全部写到一个新文件中,该新文件在文件夹myDir下. 2.源代码: test.py代码如下: import

Python操作文件、文件夹、字符串

Python 字符串操作 去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sStr1 = 'strcpy2' print sStr2 连接字符串 #strcat(sStr1,sStr2) sStr1 = 'strcat' sStr2 = 'append' sStr1 += sStr2 print sStr1 查找字符 #strchr(sStr1,sS

Python打包文件夹的方法小结(zip,tar,tar.gz等)

本文实例讲述了Python打包文件夹的方法.分享给大家供大家参考,具体如下: 一.zip ? 1 2 3 4 5 6 7 8 9 10 11 import os, zipfile #打包目录为zip文件(未压缩) def make_zip(source_dir, output_filename):   zipf = zipfile.ZipFile(output_filename, 'w')   pre_len = len(os.path.dirname(source_dir))   for pa

python 遍历文件夹 文件

python 遍历文件夹 文件 import os import os.path rootdir = "d:\data" # 指明被遍历的文件夹 for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字 for dirname in dirnames: #输出文件夹信息 print "parent is:" + parent print &q

python 遍历文件夹文件代码

import os def tree(top): for path, names, fnames in os.walk(top): for fname in fnames: yield os.path.join(path, fname) for name in tree('C:\Users\XXX\Downloads\Test'): print name python 遍历文件夹文件代码

Python 操作文件模拟SQL语句功能

Python操作文件模拟SQL语句功能 一.需求 当然此表你在文件存储时可以这样表示 1,Alex Li,22,13651054608,IT,2013-04-01 现需要对这个员工信息文件,实现增删改查操作 1. 可进行模糊查询,语法至少支持下面3种: 1. select name,age from staff_table where age > 22 2. select * from staff_table where dept = "IT" 3. select * from

操作文件夹,删除所有空文件夹

操作文件夹,删除所有空文件夹,首要条件是判断文件是否来空.即是说文件夹是存在的,没有文件存在的即为空. 整个方法中,使用迭代循环时行扫描所有目录和子目录. public static void RemoveAllEmptyDirectories(string physicalPath) { foreach (var directory in Directory.GetDirectories(physicalPath)) { RemoveAllEmptyDirectories(directory)

Directory 操作文件夹类

1.Directory 操作文件夹 CreateDirectory 创建文件夹 Delete  删除文件夹 Move  剪切文件夹 Exist  判断是否存在 GetFiles 获得指定的目录下所有文件的全路径 GetDirectory 获得指定目录下所有文件夹的全路径 2.WebBrowser浏览器控件 url 3.ComboBox下拉框控件 DropDownStyle:控制下拉框的外观样式 名字:cbo+.... 案例:日期选择器 4.点击更换图片 1).在程序加载的时候,将指定图片文件夹中

python操作文件和目录

python操作文件和目录 目录操作 # 查看当前目录 >>> os.path.abspath('.') '/Users/markzhang/Documents/python/security' # 查看当前目录 >>> os.getcwd() '/Users/markzhang/Documents/python/security' # 更改当前的工作目录 >>> os.chdir('/Users/markzhang/') >>> o