»°ËµPython£¨Èý£©Íò¶ñµÄ±àÂë
Íò¶ñµÄ±àÂë
С²Ë¶ÔÓÚÀÏʦÉÏÒ»½Ú½²µÄ²»ÊǺÜÃ÷°×£¬ÒòΪûÓÐÒ»±¾ÊéÊǽ«ÎļþÓëwebÒ»Æð½²Êڵģ¬Ëû¾ö¶¨×Ô¼ºÌ½¾¿Ò»ÏÂËüÃÇÖ®¼äµÄ²»Í¬£º
Ê×ÏÈ£¬Ð¡²ËÔÚCÅ̽¨ÁËÒ»¸öÎı¾Îĵµ file.txt,ÊäÈëËĸö×Ö£ºÎÒÊÇС²Ë¡£
È»ºó£¬Ð¡²ËÔÚshellÖÐÁ·Ï°ÆðÀ´£º
>>> file=open("c:\\file.txt","r")
>>> data=file.read()
>>> print(data)
ÎÒÊÇС²Ë
>>>
С²ËÓÐÁ˳ɾ͸У¬½Ó×ÅÊÔÒ»ÊÔÕâ¸ö£º
>>> import urllib.request
>>> page=urllib.request.urlopen("http://www.baidu.com")
>>> data=page.read()
>>> print(data)
b'<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>\xb0\xd9\xb6\xc8\xd2\xbb\xcf\xc2\xa3\xac\xc4\xe3\xbe\xcd\xd6\xaa\xb5\xc0
#ÔÚÕâÀïΪÁ˽ÚԼƪ·ùÎÒÊ¡ÂÔÁ˺óÃæÄÚÈÝ
“²»¶Ô°¡£¬ÕâЩ·´Ð±¸ÜÊÇɶ°¡£¡ºº×ÖզûÁË£¿”С²Ë¶ÔÓÚÕâÖÖÃïÊÓººÓïµÄÐÐΪ·Ç³£·ß¿®£¬“¹Ö²»µÃÖйúÈ˱à³Ì²»ÐÐÁË£¬Á¬ºº×Ö¶¼ÒªÕÛÌÚ°ëÌì¡£”
µÚ¶þÌìÒ»ÉϿΣ¬Ð¡²ËÅܵ½ÀÏʦ¸úÇ°£¬±§Ô¹ÆðÀ´£º“ÎļþºÍÍøÂç¶ÁÈ¡µÄ½á¹û²»Ò»Ñù°¡£¡Ò»¸öÕý³££¬Ò»¸ö²»ÏÔʾºº×Ö¡£”
´óÅ£ÀÏʦЦ×Å˵£º“Õâ²»ÄܹÖÄ㣬ÊÇÎÒûÓн²Çå³þ¡£”
Python 3.x ÓëPython 2.xµÄ²»Í¬µãÖ®Ò»¾ÍÊÇPython3kÒýÈëÁËbytes¶ÔÏ󣬸ղÅС²ËÔÚfileÖеõ½µÄÊÇstring£¨×Ö·û´®£©£¬¶øÔÚurlÖеõ½µÄÊÇbytes£¨×Ö½Ú£©¡£ÔÚ×îºóµÄÊä³öÀǰÃæÓÐÒ»¸öb£¬Ö¸µÄ¾ÍÊÇbytes¡£Æäʵ£¬Èç¹ûopen²ÉÓÓb”ģʽµÄʱºò£¬µÃµ½µÄÒ²ÊÇbytes£¬½«×Ö½Úת»¯¾ÍҪѧµ½½ñÌìµÄÄÚÈÝ£º±àÂë¡£
Python3kÖвÉÓÃÁ½¸öº¯ÊýÍê³ÉÕâ¸ö¹¤×÷£ºencode()ºÍdecode()¡£
¹ËÃû˼Ò壺encode()ÊǽøÐбàÂëµÄ£¬½«×Ö·û´®±àÂë³ÉÏëÒªµÄ±àÂë¸ñʽ¡£
decode()ÊǽøÐнâÂëµÄ£¬½«±àÂëµÄ×Ö½Ú½âÂëΪ×Ö·û´®¡£
³£ÓõıàÂë¸ñʽÓÐASCII¡¢unicode¡¢UTF-8¡¢big5¡¢gbk¡¢gb2312µÈ£¬asciiÓÃÓÚ±±ÃÀ×Ö·û£¬utf-8¡¢unicodeÊǹú¼Ê±ê×¼£¬big5ÊÇÖÐÎÄ·±Ì壬gbk¡¢gb2312ÊǼòÌåÖÐÎÄ¡£
С²ËµÄwebÊý¾ÝÊÇgb2312±àÂëµÄ£¬¿ÉÒÔÔÚºóÃæд
>>> content=data.decode('gb2312')
>>> print(content)
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>°Ù¶Èһϣ¬Äã¾ÍÖªµÀ </title>
Ïà¹ØÎĵµ£º
There should be one—--and preferably only one –--obvious way to do it.
......
µ±pythonÖм䴦Àí·ÇASCII±àÂëʱ£¬¾³£»á³öÏÖÈçÏ´íÎó£º
UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128)
0x??Êdz¬³ö128µÄÊý×Ö£¬pythonÔÚĬÈϵÄÇé¿öÏÂÈÏΪÓïÑԵıàÂëÊÇascii±àÂ룬ËùÒÔÎÞ·¨´¦ÀíÆäËû±àÂ룬ÐèÒªÉèÖÃpythonµÄĬÈϱàÂëΪËùÐèÒªµÄ±àÂë¡£
Ò»¸ö½â¾öµÄ·½°¸ÊÇ ......
1.¸Ä±ä±¾ÎļþµÄÊôÐÔ
import
os
import
stat
os.chmod( filename, stat.S_IWRITE )
2.¸Ä±ä±¾Ä¿Â¼¼°Æä×ÓĿ¼ÊôÐÔ
import
os
os.system(r
'
attrib -r' + path +'\\*.* /s
'
)
3.½éÉܸıäÎļþÊôÐÔµÄdosÖ¸Áî
Attrib
ÏÔʾ¡¢ÉèÖûòɾ³ýÖ¸ÅɸøÎļþ»òĿ¼µÄÖ»¶Á¡¢´æµµ¡¢ÏµÍ³ÒÔ¼°Òþ²ØÊôÐÔ¡£Èç¹ûÔÚ²»º¬²ÎÊýµÄÇ ......
1£® Ê×ÏȾÍÊÇÔÚ±àÒëÆ÷ÖаÑpython°²×°Ä¿Â¼include/Óëlibs/¼ÓÈ룬¶ÔÓÚÕâµãÎÒÔÚvc6ÖпÉÒÔ£¬µ«ÊÇÔÚdev c++Öм´Ê¹¼ÓÈëÁ˱àÒëÒ²»á³ö´í£¬ËµÕÒ²»µ½pythonÍ·Îļþ£¬Õâµã±È½ÏÓôÃÆ£¬²»¹ý¿¼Âǵ½Ò»°ãwindows±à³Ì¶¼ÓõÄÊÇvc£¬ËùÒÔ²¢Ã»ÓÐʲôӰÏì°É£¡£¡£¡
È»ºóÓÃ#include <Python.h>¾Í¿ÉÒÔ°ÑpythonµÄÖ÷Í·Îļþ°üº¬½øÀ´ÁË¡£
µ«Ê ......