# 文件的读取:
d = dict(name='Bob', age=20, score=88)
with open('C:\\Users\Administrator\Desktop\\test1.txt', 'w', encoding='utf-8')as f:
f.write('asdf')
with open('C:\\Users\Administrator\Desktop\\test1.txt', 'r', encoding='utf-8')as f:
print(f.read())
# 序列化(二进制存取和读取):
d = dict(name='Bob', age=20, score=88)
with open('C:\\Users\Administrator\Desktop\\test1.txt', 'wb')as f:
pickle.dump(d, f)
with open('C:\\Users\Administrator\Desktop\\test1.txt', 'rb')as f:
print(pickle.load(f))
# yaml文件的读取
import yaml
dic = {'a': 1}
with open('C:\\Users\Administrator\Desktop\\test1.yaml', 'w')as f:
yaml.dump(dic, f)
with open('C:\\Users\Administrator\Desktop\\test1.yaml', 'r')as f:
deviceYaml = yaml.load(f)
print(deviceYaml)
# python转换成json
import json
d = dic(name='bob', age='20')
print(json.dump(d))
'{"age": 20, "score": 88, "name": "Bob"}'
相反的json转换成python对象用load()
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
json.load(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}
*****文件的路径问题
for root, dirpaths, filenames in os.walk('D:\pycharm\PycharmWorkSpase\\appiumJianshu\PageObject'):
# 遍历所有路径
for dirpath in dirpaths:
print(os.path.join(root, dirpath))
# 遍历所有的文件路径
for filename in filenames:
print(os.path.join(root, filename))
关于open()的mode参数:
'r':读
'w':写(先把原文件的内容清空再写入新的东西)
'a':追加
'r+' == r+w(可读可写,文件若不存在就报错(IOError))
'w+' == w+r(可读可写,文件若不存在就创建)
'a+' ==a+r(可追加可写,文件若不存在就创建)
对应的,如果是二进制文件,就都加一个b就好啦:
'rb' 'wb' 'ab' 'rb+' 'wb+' 'ab+'