Python之模块(二)

os 模块

 1 import os
 2 
 3 print(os.getcwd()) #获取当前目录
 4 
 5 os.chdir("../test") #改变当前脚本目录;相对于shell下cd
 6 print(os.getcwd())
 7 
 8 print(os.curdir) #返回当前目录 (".")
 9 
10 print(os.pardir) #获取当前目录的父目录字符串名 ("..")
11 
12 os.makedirs("dirname1/dirname2") #可生成多层递归目录
13 
14 os.removedirs("dirname1") #若目录为空,则删除,并递归到上一级目录,若也为空,则删除,依次
15 
16 os.mkdir("dirname") #生成单级目录,
17 
18 os.rmdir("dirname") #删除单级目录;若目录不为空则无法删除,报错
19 
20 print(os.listdir(".")) #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表的方式打印
21 
22 os.remove() #删除一个文件
23 
24 os.rename("oldname","newname") #重命名文件/目录
25 
26 print(os.stat(".")) #获取文件/目录信息
27 
28 print([os.sep]) #输出操作系统特定的路径分隔符。win->"\"; linux->"/"
29 
30 print([os.linesep]) #输出操作系统特定的行终止符。win->"
"; linux->"
"
31 
32 print(os.pathsep) #输出用于分割文件路径的字符串。win->";"; linux->":"
33 
34 print(os.name) #输出字符串指示当前使用的平台。win->"nt"; linux->"posix"
35 
36 os.system("bash command") #运行shell命令,直接显示
37 
38 print(os.environ) #获取系统环境变量
39 
40 print(os.path.abspath(__file__)) #返回__file__绝对路径
41 
42 print(os.path.split(path)) #将path分割成目录和文件名二元组返回
43 
44 print(os.path.dirname(path)) #返回path的目录。其实就是os.path.split(path)的第一个元素
45 
46 print(os.path.basename(path)) #返回path最后的文件名。其实就是os.path.split(path)的第二个元素
47                                 如果path以/或者结尾,那么就返回空
48 print(os.path.exists(path))#如果path存在返回True,不存在返回False
49 
50 print(os.path.isabs(path)) #如果path是绝对路径,返回True,否则返回False
51 
52 print(os.path.isfile(path)) #如果path是一个存在的文件,返回True,否则返回False
53 
54 print(os.path.isdir(path)) #如果path是一个存在的目录,返回True,否则返回False
55 
56 print(os.path.join(path1,path2)) #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
57 
58 print(os.path.getatime(path)) #返回path所指向的文件或者目录的最后存取时间
59 
60 print(os.path.getmtime(path)) #返回path所指向的文件或者目录的最后修改时间
os模块

sys 模块

import sys

print(sys.argv) #命令参数list,第一个元素是程序本身路径

sys.exit() #推出程序,正常推出exit(0)

print(sys.version) #获取python解析器的版本信息

print(sys.path) #返回模块搜索路径,初始化时使用PYTHONPATH环境变量的值

print(sys.platform) #返回操作系统平台的名称
进度条
import sys
import time
for i in range(10):
    sys.stdout.write("#")
    time.sleep(1)
    sys.stdout.flush()
View Code

json 和 pickle 模块

之前的学习以中用eval内置方法可以将一个字符串转换成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就i不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值。

json:将数据转换成字符串

import json

dic = {'name':"abc"}

dic_str = json.dumps(dic)  #json字符串 把所有的引号全部变成双引号 然后在把数据变成字符串
print(dic_str){"name": "abc"}
print(type(dic_str)) #<class 'dict'>

#--------------序列化对象
f = open("hello","w")
f.write(dic_str)   #----------->json.dump(dic,f)
f.close()

#----------------------反序列化
f = open("hello","r")
data = json.loads(f.read())  #----------->data = json.load(f)
f.close()

pickle:将数据转换成字节形式。

pickle和json用法类似,但是支持的类似更多。

pickle写入数据以wb的方式,读取数据rb方式,写入的数据人看不出来,计算机能读出来。

序列化:把对象(变量)从内存中变成可存储或传输的过程称之为序列化。

序列化后可以把数据写入磁盘。

shelve 模块

shelve模块比pickle模块简单,只有一个open函数,返回值类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

import shelve

f = shelve.open(r"shelve")  #目的:将一个字典放入文本

# f["stu1_info"] = {"name":"abc","age":16}
# f["stu2_info"] = {"name":"def","age":18}
# f.close()

print(f.get("stu1_info")["name"])

f.close()

xml 模块

xml是实现不同语言或者程序之间进行数据交换的协议,跟json差不多,但是json使用起来更简单,不过,在json还没出来前,大家只能用xml,现在很多传统公司很多系统的接口主要还是xml。

xml格式 就是通过<>节点来区别数据结构的:

<?xml version='1.0'?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <dgppc>141100</dgppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <dgppc>59900</dgppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <dgppc>13600</dgppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
xml数据

xml协议在各个语言中都是支持的,在python中 可以用以下模块操作xml:

import xml.etree.ElementTree as ET

tree = ET.parse("xml_lesson")  #parse解析
root = tree.getroot()  #得到文档树
print(root.tag)

#编列xml文件
for child in root:
      print(child.tag,child.attrib,child.text) # child.tag标签的名字 child.attrib拿标签的属性
      for i in child:
            print(i.tag,i.text)  #i.text 标签实际包裹的内容

# 只遍历year节点
for node in root.iter("year"):
      print(node.tag,node.text)

#------------------------------
#修改
for node in root.iter("year"):
      new_year = int(node.text) + 1
      node.text = str(new_year)
      node.set("updated","yes")  #更改标签的属性

tree.write("abc.xml") #写入文件

#删除
for country in root.findall("country"):  #findall找标签能找多个
      rank = int(country.find("rank").text)
      if rank >50:
            root.remove(country)

tree.write("abc.xml")
View Code

自己创建xml文档:

import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = "19"

et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml",encoding="utf8",xml_declaration=True)

ET.dump(new_xml) #打印生产的格式
创建xml文档
原文地址:https://www.cnblogs.com/kaixindexiaocao/p/9794674.html