目录
文件操作的模式之读取
文件对象的操作方法之读
- 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