配置文件以及目录遍历

来源:互联网 发布:python中help的用法 编辑:程序博客网 时间:2024/06/05 16:31
#/usr/bin/python
#-*- coding:utf8 -*-

import difflib
import os

f1 = open("test1.txt", "r")
f2 = open("test2.txt", "r")

src = f1.read()
dst = f2.read()

print src
print dst

f1.close()
f2.close()

#任意类型序列的比较 (可以比较字符串)
#详细资料  http://www.pythonclub.org/python-basic/difflib
s = difflib.SequenceMatcher(lambda x: x=="", src, dst)
print s
for tag, i1, i2, j1, j2 in s.get_opcodes():
    print ("%s src[%d:%d]=%s dst[%d:%d]=%s" % (tag, i1,i2, src[i1:i2], j1, j2,dst[j1:j2]))


#现在进行配置文件的读取 从网上找的一个例子啊 内容如下
#[ODBC 32 bit Data Sources]
#ms access database = Microsoft Access Driver (*.mdb) (32 λ)
#dbase files = Microsoft dBase Driver (*.dbf) (32 λ)
#excel files = Microsoft Excel Driver (*.xls) (32 λ)
#[MS Access Database]
#driver32 = C:\WINDOWS\system32\odbcjt32.dll
#[dBASE Files]
#driver32 = C:\WINDOWS\system32\odbcjt32.dll
#[Excel Files]
#driver32 = C:\WINDOWS\system32\odbcjt32.dll

import ConfigParser

config = ConfigParser.ConfigParser()
config.add_section("ODBC Driver Count")
config.set("ODBC Driver Count", "count", 2)
f = open("ODBC.ini", "a+")
config.write(f)
f.close()

#可以查看到文件已经添加了一个count

#现在删除一个记录
config.read("ODBC.ini")
config.remove_option("ODBC Driver Count", "count")
config.remove_section("ODBC Driver Count")
f = open("ODBC.ini", "w+")
config.write(f)
f.close()

#可以看见count记录没有了

#现在遍历一个文件夹下的所有文件
def ShowDir(path):
    list_file = os.listdir(path)
    for p in list_file:
        pathname = os.path.join(path, p)
        if not os.path.isfile(pathname): #如果是文件
            ShowDir(pathname)  #继续遍历
        else:
            print pathname  #否则打印

path = "/home/python/"
ShowDir(path)

print
print
print
#使用walk函数来遍历
def ShowDir2(path):
    for root, dirs, files in os.walk(path, True):
        for filepath in files:
            print os.path.join(root, filepath)

ShowDir2(path)

print
print
print
#再来一种
def ShowDir3(path, dirname, names):
    for filepath in names:
        print os.path.join(dirname, filepath)

os.path.walk(path, ShowDir3, ())



QQ交流群: 204944806

0 0
原创粉丝点击