Python教程

Python文件的读取

本文主要是介绍Python文件的读取,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录

  • 文件操作的模式之读取
  • 文件对象的操作方法之读取

文件操作的模式之读取

在这里插入图片描述

文件对象的操作方法之读

在这里插入图片描述

  • seek函数可以指定读取文件的位置,seek(0)表示从头开始

with open可以自动关闭文件

实战

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     : 2021/8/22 11:11
# @Author   : InsaneLoafer
# @File     : package_open.py

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', encoding='utf-8')
    f.write('# coding:utf-8\n')
    f.close()

class Open(object):
    def __init__(self, path, mode='w', is_return=True):
        self.path = path
        self.mode = mode
        self.is_return = is_return

    def write(self, message):
        f = open(self.path, mode=self.mode, encoding='utf-8')
        try:
            if self.is_return and message.endswith('\n'):
                message = '%s\n' % message
            f.write(message)
        except Exception as e:
            print(e)
        finally:
            f.close()

    def read(self, is_strip=True):
        result = []
        with open(self.path, mode=self.mode, encoding='utf-8') as f:
            data = f.readlines()
        for line in data:
            if is_strip:
                temp =line.strip()
                if temp != '':
                    result.append(temp)
            else:
                if line != '':
                    result.append(line)
        return result

if __name__ == '__main__':
    current_path = os.getcwd()
    # path = os.path.join(current_path, 'test2')
    # create_package(path)
    open_path = os.path.join(current_path, 'b.txt')
    o = Open('package_datetime.py', mode='r')
    # o.write('你好 娃娃')
    data = o.read()
    print(data)
['#!/usr/bi# -*- coding: utf-8 -*-', '# @Time     : 2021/8/20 21:32', '# @Author   : InsaneLoafer', '# @File     : package_datetime.py', 'from datetime import datetime', 'from datetime import timedelta', 'now = datetime.now()', 'print(now, type(now))', "now_str = now.strftime('%Y-%m-%d %H:%M:%S')", 'print(now_str, type(now_str))', "now_obj = now.strptime(now_str, '%Y-%m-%d %H:%M:%S')", "print('====')", 'print(now_obj, type(now_obj))', 'three_days = timedelta(days=3)', 'after_three_day = now + three_days', 'print(after_three_day)', "print('-------')", "after_three_day_str = after_three_day.strftime('%Y/%m/%d %H:%M:%S')", 'before_three_days = now - three_days', 'print(before_three_days)', 'one_hour = timedelta(hours=1)', 'before_one_hour = now - one_hour', 'print(before_one_hour)']

Process finished with exit code 0
这篇关于Python文件的读取的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!