没有合适的资源?快使用搜索试试~ 我知道了~
执行已编译的代码execfile("hello.py")defEXECFILE(filename,locals=None,globals=None):execcompile(open(filename).read(),filename,"exec")inlocals,globalsEXECFILE("hello.py")helloagain,andwelcometotheshowhelloagain,andwelcometotheshow显式地访问__builtin__模块中的函数Python还提供了execfile函数,一个从文件加载代码,编译代码,执行代码的快捷方式.使用execfile函
资源推荐
资源详情
资源评论


















python标准库学习(后篇)标准库学习(后篇)
执行已编译的代码
execfile("hello.py")
def EXECFILE(filename, locals=None, globals=None):
exec compile(open(filename).read(), filename, "exec") in locals, globals
EXECFILE("hello.py")
hello again, and welcome to the show
hello again, and welcome to the show
显式地访问 _ _builtin_ _ 模块中的函数
def open(filename, mode="rb"):
import _ _builtin_ _
file = _ _builtin_ _.open(filename, mode)
if file.read(5) not in("GIF87", "GIF89"):
raise IOError, "not a GIF file"
file.seek(0)
return file
fp = open("samples/sample.gif")
print len(fp.read()), "bytes"
fp = open("samples/sample.jpg")
print len(fp.read()), "bytes"
3565 bytes
Traceback (innermost last):
File "builtin-open-example-1.py", line 12, in ?
File "builtin-open-example-1.py", line 5, in open
IOError: not a GIF file
Python 还提供了 execfile 函数, 一个从文件加载代码, 编译代码, 执行代码的快捷方式.
使用 execfile 函数

# python imports this module by itself, so the following
# line isn't really needed
# python 会自动导入该模块, 所以以下这行是不必要的
# import exceptions
class HTTPError(Exception):
# indicates an HTTP protocol error
def _ _init_ _(self, url, errcode, errmsg):
self.url = url
self.errcode = errcode
self.errmsg = errmsg
def _ _str_ _(self):
return (
"<HTTPError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)
try:
raise HTTPError("http://www.python.org/foo", 200, "Not Found")
except HTTPError, error:
print "url", "=>", error.url
print "errcode", "=>", error.errcode
print "errmsg", "=>", error.errmsg
raise # reraise exception
url => http://www.python.org/foo
errcode => 200
errmsg => Not Found
Traceback (innermost last):
File "exceptions-example-1", line 16, in ?
HTTPError: <HTTPError for http://www.python.org/foo: 200 Not Found>
显式地访问 _ _builtin_ _ 模块中的函数
def open(filename, mode="rb"):
import _ _builtin_ _
file = _ _builtin_ _.open(filename, mode)
if file.read(5) not in("GIF87", "GIF89"):
raise IOError, "not a GIF file"
file.seek(0)
return file
fp = open("samples/sample.gif")
print len(fp.read()), "bytes"
fp = open("samples/sample.jpg")
print len(fp.read()), "bytes"
3565 bytes
Traceback (innermost last):
File "builtin-open-example-1.py", line 12, in ?
File "builtin-open-example-1.py", line 5, in open
IOError: not a GIF file
使用 exceptions 模块

# python imports this module by itself, so the following
# line isn't really needed
# python 会自动导入该模块, 所以以下这行是不必要的
# import exceptions
class HTTPError(Exception):
# indicates an HTTP protocol error
def _ _init_ _(self, url, errcode, errmsg):
self.url = url
self.errcode = errcode
self.errmsg = errmsg
def _ _str_ _(self):
return (
"<HTTPError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)
try:
raise HTTPError("http://www.python.org/foo", 200, "Not Found")
except HTTPError, error:
print "url", "=>", error.url
print "errcode", "=>", error.errcode
print "errmsg", "=>", error.errmsg
raise # reraise exception
url => http://www.python.org/foo
errcode => 200
errmsg => Not Found
Traceback (innermost last):
File "exceptions-example-1", line 16, in ?
HTTPError: <HTTPError for http://www.python.org/foo: 200 Not Found>
使用 os 模块重命名和删除文件

import os
import string
def replace(file, search_for, replace_with):
# replace strings in a text file
back = os.path.splitext(file)[0] + ".bak"
temp = os.path.splitext(file)[0] + ".tmp"
try:
# remove old temp file, if any
os.remove(temp)
except os.error:
pass
fi = open(file)
fo = open(temp, "w")
for s in fi.readlines():
fo.write(string.replace(s, search_for, replace_with))
fi.close()
fo.close()
try:
# remove old backup file, if any
os.remove(back)
except os.error:
pass
# rename original to backup...
os.rename(file, back)
# ...and temporary to original
os.rename(temp, file)
#
# try it out!
file = "samples/sample.txt"
replace(file, "hello", "tjena")
replace(file, "tjena", "hello")
使用 os 列出目录下的文件
import os
for file in os.listdir("samples"):
print file
sample.au
sample.jpg
sample.wav
...
getcwd 和 chdir 函数分别用于获得和改变当前工作目录
使用 os 模块改变当前工作目录
import os
# where are we?
cwd = os.getcwd()
print "1", cwd
# go down
os.chdir("samples")
print "2", os.getcwd()
# go back up
os.chdir(os.pardir)
print "3", os.getcwd()
1 /ematter/librarybook
2 /ematter/librarybook/samples
3 /ematter/librarybook

makedirs 和 removedirs 函数用于创建或删除目录层
使用 os 模块创建/删除多个目录级
import os
os.makedirs("test/multiple/levels")
fp = open("test/multiple/levels/file", "w")
fp.write("inspector praline")
fp.close()
# remove the file
os.remove("test/multiple/levels/file")
# and all empty directories above it
os.removedirs("test/multiple/levels")
removedirs 函数会删除所给路径中最后一个目录下所有的空目录. 而 mkdir 和 rmdir 函数只能处理单个目录级
使用 os 模块创建/删除目录
import os
os.mkdir("test")
os.rmdir("test")
os.rmdir("samples") # this will fail
Traceback (innermost last):
File "os-example-7", line 6, in ?
OSError: [Errno 41] Directory not empty: 'samples'
如果需要删除非空目录, 你可以使用 shutil 模块中的 rmtree 函数
>>> import shutil
shutil.rmtree("d:\\a")
复制文件目录(包括内部文件)
>>> shutil.copytree("d:\\new","d:\\a")
复制文件操作:
shutil.copyfile("d:\\new\\a.txt","d:\\a.txt")
目录或文件的移动操作
shutil.move("d:\\new\\a.txt","d:\\")
使用 os 模块获取文件属性
剩余58页未读,继续阅读
资源评论


weixin_38528180
- 粉丝: 4
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- 基于单片机的智能控制仪表简单设计.doc
- 大数据背景下企业人力资源绩效管理分析.docx
- 数学新设计同步人教B版必修三课件:第一章算法初步1.11算法的概念.ppt
- 信息产业与信息化发展分概要.doc
- radar-移动应用开发资源
- 物联网背景下产品设计中的人性化研究.docx
- 驻地网流量及大数据运营方案.ppt
- 教学课件4-3-网站用户体验.ppt
- 主机-网络-存储-维保服务技术方案.docx
- 基于STC8系列的ECBM函数库V3-单片机开发资源
- Apache-php-mysql在windows下安装与配置图解版.doc
- 西门子PLC自动控制系统故障现象分析及处理探析.docx
- PIC单片机控制直流电机转速大学本科方案设计书.doc
- 云计算技术在计算机网络安全存储中的应用路径.docx
- PLC和配置技术交通灯控制系统设计逐句翻译.doc
- cto下载年上半年数据库系统工程师上午(未排版).doc
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



安全验证
文档复制为VIP权益,开通VIP直接复制
