python文件的操作笔记

# 文件的读取:
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+'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值