# -*- coding: utf-8 -*-import os
# rename the file
files = os.listdir(".")
for filename in files:
pos = filename.find(".")
if filename[pos+1:] == "html":
newname = filename[:pos+1]+"html"
os.rename(filename, newname)
# -*- coding: utf-8 -*-import os
# rename the file
files = os.listdir(".")
for filename in files:
li = os.path.splitext(filename)
if li[1] == ".html":
newname = li[0] + ".htm"
os.rename(filename, newname)
# -*- coding: utf-8 -*-import glob
# rename the file
files = glob.glob("d:\\w*\\*.txt")
for filename in files:
li = os.path.splitext(filename)
if li[1] == ".html":
newname = li[0] + ".htm"
os.rename(filename, newname)
文件内容的搜索和替换
# -*- coding: utf-8 -*-import re
# find in the file
f1 = file("hello.txt", "r")
count = 0for s in f1.readlines():
li = re.findall("hello", s)
if len(li) > 0:
count = count + li.count("hello")
print"Find "+str(count) + " hello"
f1.close()
Find 2 hello
# -*- coding: utf-8 -*-import re
# replace in the file
f1 = file("hello.txt", "r")
f2 = file("hello2.txt", "w")
for s in f1.readlines():
f2.write(s.replace("hello","hi"))
f1.close()
f2.close()
文件的比较
# -*- coding: utf-8 -*-import difflib
# compare the file
f1 = file("hello.txt", "r")
f2 = file("hi.txt", "r")
src = f1.read()
dst = f2.read()
print src
print dst
s = difflib.SequenceMatcher(lambda x: x=="", src, dst)
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])
hello world
hi world
equal src[0:1]=h dst[0:1]=h
replace src[1:5]=ello dst[1:2]=i
equal src[5:11]= world dst[2:8]= world
配置文件的读写
# -*- coding: utf-8 -*-import ConfigParser
# read the .ini file
config = ConfigParser.ConfigParser()
config.read("ODBC.ini")
sections = config.sections()
print"config section:", sections
o = config.options("ODBC 32 bit Data Sources")
print"config items:", o
v = config.items("ODBC 32 bit Data Sources")
print"content: ", v
# access the options and items
access = config.get("ODBC 32 bit Data Sources", "MS Access Database")
print access
excel = config.get("ODBC 32 bit Data Sources", "Excel Files")
print excel
dBASE = config.get("ODBC 32 bit Data Sources", "dBASE Files")
print dBASE
# -*- coding: utf-8 -*-import ConfigParser
# remove items in the .ini file
config = ConfigParser.ConfigParser()
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()
目录的创建和遍历
# -*- coding: utf-8 -*-import os
# create the directory
os.mkdir("hello")
os.rmdir("hello")
os.makedirs("hello/world")
os.removedirs("hello/world")
# -*- coding: utf-8 -*-import os,os.path
# walk the directorydefListDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
ifnot os.path.isfile(pathname):
ListDir(pathname)
else:
print pathname
if __name__=="__main__":
path = r".";
ListDir(path)
# -*- coding: utf-8 -*-import os
# walk the directorydefListDir(path):for root,dirs,files in os.walk(path):
for filepath in files:
print os.path.join(root, filepath)
if __name__=="__main__":
path = r".";
ListDir(path)
# -*- coding: utf-8 -*-import sys,time
# standard error
sys.stderr = open("record.log", "a")
f = open(r"hello.txt","r")
t = time.strftime("%Y-%m-%d%X", time.localtime())
context = f.read()
if context:
sys.stderr.write(t+" "+context)
else:
raise Exception, t+"exceptin information"
# -*- coding: utf-8 -*-# file input streamdefFileInputStream(filename):try:
f = open(filename)
for line in f:
for byte in line:
yield byte
except StopIteration, e:
f.close()
return# file output streamdefFileOutputStream(inputStream, filename):try:
f = open(filename,"w")
whileTrue:
byte = inputStream.next()
f.write(byte)
except StopIteration, e:
f.close()
returnif __name__ == "__main__":
FileOutputStream(FileInputStream("hello.txt"),"hello2.txt")
# -*- coding: utf-8 -*-import time, os
# show the properties of filesdefShowFileProperties(path):for root, dirs, files in os.walk(path, True):
print"location:"+root
for filename in files:
state = os.stat(os.path.join(root, filename))
info = "file name:" + filename+ " "
info = info +"size:"+("% d "% state[-4]) + ""
t = time.strftime("%Y-%m-%d%X", time.localtime(state[-1]))
info = info +"created time:"+ t + ""
t = time.strftime("%Y-%m-%d%X", time.localtime(state[-2]))
info = info +"last modified time:"+ t + ""
t = time.strftime("%Y-%m-%d%X", time.localtime(state[-3]))
info = info +"last access time:"+ t + ""print info
if __name__ == "__main__":
path = r"."
ShowFileProperties(path)