Python中的OS模块
os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,如posix或NT系统平台,os模块会根据不同的平台进行相应的操作.本节内容将对os模块提供的函数进行详细的解读.
1.1 文件操作函数
1.1.1 open()函数提供创建、打开、修改文件的功能。
Example 1-1. Using the os Module to Rename and Remove Files
#Filename: os-example-1.py
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")
1.1.2 rename()和remove()函数,对文件进行重命名和删除操作.请参照例1-1
1.2 目录操作
1.2.1 listdir()函数,返回指定目录下所有文件名,并保存于一列表中.但当前目录标记(.)和父目录标记(..)不在其中.
Example 1-2. Using the os Module to List the Files in a Directory
File: os-example-2.py
import os
for file in os.listdir("samples"):
相关文档:
很长的一段代码,但很清楚。哈哈。
import os
from time import strftime
stamp=strftime("%Y-%m-%d %H:%M:%S")
logfile = 'F:\\test\\m-php-framework\\tmp\logs\\error_report.log'
path = 'F:\\test\\'
files = os.listdir(path)
bytes = 0
numfiles = 0
for f in files:
if f.startswith('t'): ......
Python MySQLdb 查询返回字典结构 smallfish
MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。
默认程序:
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', d ......
[原创]Python代码模块热更新机制实现(reload)
by AKara 2009-05-17 @ http://blog.csdn.net/akara @ akaras@163.com
---------------------------------------------------------------------
对一个游戏来说,无论是client或server都非常需要一套代码热更新的机制。
它能大大提高开发效率,又能超乎玩 ......
python cookbook
Recipe 2.5. Counting Lines in a File
,
今日发现一个新函数
enumerate
。一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:
for
i
in
range
(0
,
len
(list
)):
&n ......
全文来自:IT工程技术网 http://www.systhinker.com/html/91/n-11591.html
昨天和飞天舞者讨论静态类型语言和动态类型语言优劣比较的时候,说到Python没有重载机制的问题。
后来想想挺有意思的,把思考的经过记录下来,欢迎拍砖。
重载(overload)和覆盖(override),在C++,Java,C#等静态类型语言类型语言中,这两个 ......