python 3.x 學習筆記8 (os模組及xml修改),python3.x
1.os模組操作
os.getcwd(): # 查看當前所在路徑。
os.listdir(path): # 列舉目錄下的所有檔案,返回的是清單類型。
os.path.abspath(path): # 返回path的絕對路徑。
os.path.join(path1,path2,...): # 將path進行組合,若其中有絕對路徑,則之前的path將被刪除。
os.path.dirname(path): # 返回path中的檔案夾部分,結果不包含'\'
os.path.basename(path): # 返回path中的檔案名稱。
os.path.getmtime(path): # 檔案或檔案夾的最後修改時間,從新紀元到訪問時的秒數。
os.path.getatime(path): # 檔案或檔案夾的最後訪問時間,從新紀元到訪問時的秒數。
os.path.getctime(path): # 檔案或檔案夾的建立時間,從新紀元到訪問時的秒數。
os.path.getsize(path): # 檔案或檔案夾的大小,若是檔案夾返回0
os.path.exists(path): # 檔案或檔案夾是否存在,返回True 或 False。
2.xml的使用
xml建立
from xml.etree import ElementTree as ETdef build_sitemap(): urlset = ET.Element("urlset") # ET.Element建立一個根節點,標籤為urlset url = ET.SubElement(urlset,"url") # ET.SubElement在根節點urlset下建立子節點 loc = ET.SubElement(url,"loc",attrib={"name":"百度"}) #attrib為建立屬性 loc.text = "http://www/baidu.com" #loc.test 為寫入內容 time = ET.SubElement(url,"time") time.text = "2018-1-30" change = ET.SubElement(url,"change") change.text = "daily" priority = ET.SubElement(url,"priority") priority.text = "1.0" tree = ET.ElementTree(urlset) tree.write("set.xml",'utf-8') #寫入時加上‘utf-8’可以轉譯中文,不會有亂碼if __name__ == '__main__': build_sitemap()
產生的xml
<urlset> <url> <loc name="百度">http://www/baidu.com</loc> <time>2018-1-30</time> <change>daily</change> <priority>1.0</priority> </url></urlset>
下面是要修改的檔案
<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>
修改程式
import xml.etree.ElementTree as ETtree = ET.parse('xmltest.xml')root = tree.getroot()#修改for node in root.iter('year'): new_year = int(node.text) + 1 node.text = str(new_year) node.set('updated_by','hsj')tree.write('xmltest2.xml')#刪除for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country)tree.write('xmltest3.xml')