Skip to main content

Python 文件的创建和写入

Published 1 min readMarkdown
Python 文件的创建和写入

文件的创建和写入

利用内置函数open获取文件对象

功能
  • 生成文件对象,进行创建,读写操作
用法
  • open(path, mode)
参数说明
  • path:文件路径
  • mode:操作模式
返回值
  • 文件对象
举例
  • f = open('d://a.txt', 'w')

文件操作的模式之写入

模式介绍
w创建文件
w+创建文件并读取文件
wb二进制形式创建文件
wb+二进制形式创建或追加内容
a追加内容
a+读写模式的追加
ab+二进制形式读写追加

文件对象的操作方式之写入保存

方法名参数介绍举例
writeMessage写入信息f.write('hello\n')
writelinesMessage_list批量写入f.writelines(['hello\n', 'world\n'])
close无关闭并保存文件f.close()
  • 操作完成后,必须使用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('你好 小慕')

5 views

No comments yet. Be the first to comment.

More from this blog