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"):
Ïà¹ØÎĵµ£º
»ù±¾É϶¼ÊÇʹÓÃpythonÀ´½âÎöxmlÎļþµÄ¡£
±ÈÈçÎÒÒª½«ÄÚÈÝΪ
<?xml version="1.0" encoding="utf-8"?>
<root>
<book isbn="34909023">
<author>
&n ......
ÔÚLearning Python 3rd ÀïµÚÈý²¿·ÖÁ·Ï°ÌâÓеÀÌ⣺
1.c ±àдfor Ñ»·£¬¶ÔÓÚ×Ö·û´®S£¬·µ»ØÒ»¸öеÄÁÐ±í£¬ÆäÖаüº¬ÁË×Ö·û´®Ã¿¸ö×Ö·ûµÄASCIIÂë¡£
ÎÒµÄ˼·ÊÇ£º
for i in S:
L = [ord(i) for i in S] #Áбí½âÎöµÄ˼·
ÎҵĴíÎó˼·£º
for i in S:
L = L.append(ord(i))
Ìáʾ¿Õ¶ ......
“¹þ¹þ£¡ÖªµÀÎÒ²Ù×÷Ö®ÍõС°×µÄÀ÷º¦ÁË°É£¡”
ÿµ±ÖÜÁùÍíÉÏ£¬Ð¡°××ÜÊÇÒª¸úËÞÉáµÄµÜÐÖÌô¼¸¾ÖħÊÞ¡£Æ¾½è×Å·çɧµÄ×ßλºÍâ«ËöµÄÒâʶ£¬Ð¡°××ÜÊÇЦµÀ×îºó¡£Õâ²»£¬Ð¡°×ÓÖÒ»´ÎÈ¡µÃÁËÒÔÒ»µÐ¶þµÄʤÀû¡£
“Ö÷ÒªÊǶàÏß²Ù×÷£¡”ÕâÊÇС°×¶Ô×Ô¼ºÊ¤ÀûµÄ×ܽ ......
myDict = { 'item1' : [ 7, 1, 9], 'item2' : [8, 2, 3], 'item3' : [ 9, 3, 11 ] }
def sortDic(Dict,valuePostion):
return sorted(Dict.items(),key=lambda e:e[1][valuePostion])
//°´valueµÄµÚ3¸öÖµÅÅÐò
sortDic(myDict,2)
[('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])]
//°´valueµÄµÚ ......
³õѧPython£¬Õâô×öºÃÏñÓеã2£¬´ÕºÏÄÜÓãº
class MyClass():
def __init__(self, n = 10):
self._Field = n
def __getitem__(self, range):
return MyClass(self._Field)
obj1 = MyClass()
obj2 = obj1
obj3 = obj1[:]
obj1._Field = 100
obj4 = MyClass(123)
print obj1._Field, obj2. ......