open(path, mode)
path
:文件路径mode
:操作模式f = open('d://a.txt', 'w')
模式 | 介绍 |
---|---|
w | 创建文件 |
w+ | 创建文件并读取文件 |
wb | 二进制形式创建文件 |
wb+ | 二进制形式创建或追加内容 |
a | 追加内容 |
a+ | 读写模式的追加 |
ab+ | 二进制形式读写追加 |
方法名 | 参数 | 介绍 | 举例 |
---|---|---|---|
write | Message | 写入信息 | f.write(‘hello\n’) |
writelines | Message_list | 批量写入 | f.writelines([‘hello\n’, ‘world\n’]) |
close | 无 | 关闭并保存文件 | f.close() |
# coding:utf-8
import os
def create_package(path):
if os.path.exists(path):
raise Exception('%s 已经存在不可创建' % path)
os.makedirs(path)
init_path = os.path.join(path, '__init__.py')
f = open(init_path, 'w')
f.write("# coding:utf-8\n")
f.close()
class Open(object):
def __init__(self, path, mode='w', is_retern=True):
self.path = path
self.mode = mode
self.is_retern = is_retern
def write(self, message):
f = open(self.path, mode=self.mode)
if self.is_retern:
message = '%s\n' % message
f.write(message)
f.close()
if __name__ == '__main__':
current_path = os.getcwd()
# path = os.path.join(current_path, 'test1')
# create_package(path)
open_path = os.path.join(current_path, 'b.txt')
o = Open(open_path)
o.write('你好 小慕')
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有