一、操作目录
1.查看系统
>>> import os
>>> os.name # 操作系统类型
'posix'
os.uname()
2.查看环境变量
os.environ
"""差啊看环境变量列表"""
os.environ.get('PATH')
"""得到环境变量值"""
3.目录操作
# 查看当前目录的绝对路径:
os.path.abspath('.')
'/Users/michael'
#在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
os.rmdir('/Users/michael/testdir')
"""要拆分路径时,也不要直接去拆字符串,而要通过os.path.split()函数,
这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名:"""
os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')
"""os.path.splitext()可以直接让你得到文件扩展名,"""
os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')
# 对文件重命名:
os.rename('test.txt', 'test.py')
# 删掉文件:
os.remove('test.py')
"""比如我们要列出当前目录下的所有目录"""
[x for x in os.listdir('.') if os.path.isdir(x)]
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]
"""要列出所有的.py文件"""
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']
4.用递归法打印某个目录下的所有文件以及子目录下文件
import os
def print_file(path):
if os.path.isfile(path):
print(path)
else:
listdir = os.listdir(path)
dirlist = [x for x in listdir if os.path.isdir(os.path.join(path, x))]
filelist = [x for x in listdir if os.path.isfile(os.path.join(path, x))]
if dirlist:
for dirpath in dirlist:
print_file(os.path.join(path,dirpath))
for filepath in filelist:
print(os.path.join(path,filepath))
print_file(r"E:\soft\python3")
5.简化版
import os
def fi(path):
if os.path.isfile(path):
print(path)
else:
L = os.listdir(path)
for i in L:
fi(os.path.join(path, i))
fi(r"E:\soft")
6.系统函数os.work()版
import os
path ="E:\soft"
for root,dirs,files in os.walk(path):
for file in files:
print(os.path.join(root,file))
二、JSON
1、字典转化成字符串
>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'
2、字符串转化成字典
>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}
3、类转化成字符串
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def student2dict(std):
return {
'name': std.name,
'age': std.age,
'score': std.score
}
print(json.dumps(s, default=student2dict))
或者:
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
print(json.dumps(s, default=lambda obj: obj.__dict__))
4、同样的道理,如果我们要把JSON反序列化为一个Student
对象实例,loads()
方法首先转换出一个dict
对象,然后,我们传入的object_hook
函数负责把dict
转换为Student
实例:
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
5、总结
dumps()
方法返回一个str
,内容就是标准的JSON。类似的,
dump()
方法可以直接把JSON写入一个file-like Object
。要把JSON反序列化为Python对象,用
loads()
或者对应的load()
方法,前者把JSON的字符串反序列化,后者从file-like Object
中读取字符串并反序列化如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。
6.思考:
obj = dict(name='小明', age=20)
"""obj是python对象"""
s = json.dumps(obj, ensure_ascii=True)
"""s是json字符串"""
由于JSON标准规定JSON编码是UTF-8,所以我们总是能正确地在Python的str
与JSON的字符串之间转换。
如果ensure_ascii为true(默认值),则保证输出转义所有传入的非ASCII字符。如果ensure_ascii为false,则这些字符将按原样输出。
答:ensure_ascii = True,此时,非ascii 编为unicode编码。否则原样输出。