python´¦ÀíXML
»ù±¾É϶¼ÊÇʹÓÃpythonÀ´½âÎöxmlÎļþµÄ¡£
±ÈÈçÎÒÒª½«ÄÚÈÝΪ
<?xml version="1.0" encoding="utf-8"?>
<root>
<book isbn="34909023">
<author>
dikatour
</author>
</book>
</root>
дÈëµ½xmlstuff.xmlÎļþÖÐÈ¥¡£
ÆäʵҲºÜ¼òµ¥£¬»ù±¾ÔÀíÈçÏ£º
ÎÒʹÓÃxmlµÄDOM·½Ê½£¬ÏÈÔÚÄÚ´æÖд´½¨Ò»¸ö¿ÕµÄDOMÊ÷£¬È»ºó²»¶ÏÔö¼ÓÎÒÒªµÄ½Úµã£¬×îºóÐγÉÎÒÏëÒªµÄDOM£¬×îºóÊä³öµ½ÎļþÖÐÈ¥¡£
1.ÎÒʹÓÃxml.dom.minidomÕâ¸ömoduleÀ´´´½¨xmlÎļþ
from xml.dom import minidom
2. ÿ¸öxmlÎļþ¶¼ÊÇÒ»¸öDocument¶ÔÏó,´ú±í×ÅÄÚ´æÖеÄDOMÊ÷
doc = minidom.Document()
3.ÓÐÁ˿յÄDOMÊ÷ºó£¬ÎÒÃÇÔÚÉÏÃæÌí¼Ó¸ù½Úµã
rootNode = doc.createElement("root")
doc.appendChild(rootNode) #×¢ÒâpythonµÄlibrary referenceÀï˵,createElementºó²¢Ã»Óн«½Úµã¶ÔÏó¼Óµ½DOMÊ÷ÉÏ£¬ÐèÒª×Ô¼ºÊÖ¹¤¼ÓÉÏ
4.´´½¨ÆäËüµÄ½Úµã
5.Êä³öµ½xmlÎļþÖÐÈ¥
doc.writexml(f, "\t", "\t", "\n", "utf-8") #µÚÒ»¸ö²ÎÊýf¾ÍÊÇÄãµÄÄ¿±êÎļþ¶ÔÏ󣬵ڶþ¸ö²ÎÊýºÃÏñÊÇ<?xml>ºÍÏÂÃæÒ»¸ö¸ù½ÚµãµÄËõ½øÅÅÁиñʽ,
µÚÈý¸ö²ÎÊýºÃÏñÊÇÆäËû½ÚµãÓë×Ó½ÚµãµÄËõ½øÅÅÁиñʽ£¬µÚËĸö²ÎÊýÖÆ¶¨ÁË»»Ðеĸñʽ(Èç¹ûÄãÌîÈë" "£¬ÄǾͲ»»»ÐÐÁË£¬ËùÓеÄxml¶¼ËõÔÚÁËÒ»ÐÐÉÏÃæ :) )
£¬µÚÎå¸ö²ÎÊýÖÆ¶¨ÁËxmlÄÚÈݵıàÂë¡£³ýÁ˵ÚÒ»¸ö²ÎÊýÊDZØÐëµÄ£¬ÆäËû²ÎÊý¶¼ÊÇ¿ÉÑ¡ÔñµÄ¡£
×îÖÕ´úÂëÈçÏÂ(Õâ¸ö³ÌÐòûʲô¼ÛÖµ£¬Ö»ÊÇÓÃÀ´²âÊÔÑéÖ¤×Ô¼ºµÄÏë·¨,Äã¸ü¿ÉÄܶ¨ÒåÒ»¸ö¼òµ¥Àà»òº¯Êý£¬½«ÄãµÄÊý¾Ý½á¹¹ÐòÁл¯µ½xmlÎļþÖÐ)£º
from xml.dom import minidom
import traceback
try:
f = open("xmlstuff.xml", "w")
try:
doc = minidom.Document()
rootNode = doc.createElement("root")
Ïà¹ØÎĵµ£º
¶ÓÁУº
Óë¶ÑÕ»ÀàËÆ£¬Í¨¹ýpythonµÄÁбíÀàÐÍÀ´ÊµÏÖ£¬²Î¿¼ help(list)
shoplist=['apple','mango','carrot','banana']
print 'I have',len(shoplist),'items to purchase'
print 'these items are:'
for item in shoplist:
print item,
shoplist.append('rice')
print 'my shopping list is now', shoplist
shoplist. ......
1.open
ʹÓÃopen´ò¿ªÎļþºóÒ»¶¨Òª¼ÇµÃµ÷ÓÃÎļþ¶ÔÏóµÄclose()·½·¨¡£±ÈÈç¿ÉÒÔÓÃtry/finallyÓï¾äÀ´È·±£×îºóÄܹرÕÎļþ¡£
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
×¢£º²»Ä ......
ÓÃPythonÌáÈ¡Îļþ¼ÐϵÄÌØ¶¨À©Õ¹ÃûµÄÎļþ
²»ÖªµÀʲôʱºò£¬ÍøÏÐ×ÅûÓ㬹ÒÁ˸ölinuxµÄÊÓÆÁ½Ì³Ì£¬ÀïÃæÓкܶà¸öÎļþ¼Ð£¬ÓкܶàÎ޹صÄÎļþ¡£Õâ¶ÔÓÚÏñÎÒûÊÕ²ØÀ¬»øÎļþñ±ºÃµÄÈËÀ´Ëµ£¬¼òÖ±ÊÇ ......
ÕýÔò±í´ïʽÊǸöħ¹í£¬Ò²ÊǸöÌìʹ¡£ÔÚÄãûÓÐÕÆÎÕËü֮ǰ£¬ËüÊÇħ¹í£¬ÔÚÄãÕÆÎÕËüºó£¬ËüÊÇÌìʹ£¬µ«ÊÇ£¬Ê±
²»Ê±»¹ÊÇÒªÌø³öÀ´£¬¸øÄãµ÷Ƥµ·µ°Ò»·¬¡£
Ò»¸öÕýÔò±í´ïʽ¾ÍÊÇÓÉÆÕͨ×Ö·ûÒÔ¼°ÌØÊâ×Ö·û×é³ÉµÄÎÄ×Öģʽ£¬¸ÃģʽÃèÊöÔÚ²éÕÒÎÄ×ÖÖ÷Ìåʱ´ý
Æ¥ÅäµÄÒ»¸ö»ò¶à¸ö×Ö·û´®¡£ÕýÔò±í´ïʽ×÷Ϊһ¸öÄ£°å£¬½«Ä³¸ö×Ö·ûģʽÓëËùËÑË÷µÄ ......
µ±ÎÒÃÇÕâÑù½¨Á¢Îļþʱ
f =
file('x1.txt', 'w')
f.write(u'ÖÐÎÄ')
f.colse()
Ö±
½Ó½á¹ûÓ¦¸ÃÊÇÀàËÆ
f.write(u'ÖÐÎÄ')
UnicodeEncodeError: 'ascii'
codec can't encode characters in position 0-16: ordinal not in
range(128)
ÒªÖ±½Óд utf-8 ÎļþÔõô°ìÄØ?
import codecs
f = codecs. ......