目标:
自写一个包,提供关于字符串和文件的模块
要求对异常可以检测
str_tools.py:
def str_reverse(s):
"""
:param s: 传入的字符串
:return: 反转后的字符串
"""
# i = -1
# j = 0
# s2 = ""
# while i >= (-len(s)):
# s2 += s[i]
# i -= 1
# j += 1
# return s2
return s[::-1] # 开始:结束:步长,如果不写则是从头至尾,-1表示反着取
def str_substr(s, x, y): # 左闭右闭
"""
返回截取的字符串,按照左闭右闭,且非下标而是位序
:param s: 字符串
:param x: 起始处
:param y: 结束处
:return: 截取的字符串
"""
# x-=1
# y-=1
# s2 = ""
# while x <= y:
# s2 += s[x]
# x += 1
# return s2
return s[x - 1:y] # 省略了:1
# 用于本文件内测试运行,但是当被导入时不会执行下面的语句
if __name__ == '__main__':
str_reverse("测试成功")
str_substr("测试成功", 3, 4)
file_tools.py
def openfile(path, mode, ec='utf-8'):
try:
opf = open(path, mode, encoding=ec)
except FileNotFoundError as noex:
print(">︿< 没有该文件,产生了报错:", noex)
except Exception as x:
print("(*゜ー゜*)文件存在,但是有其他问题:", x)
else:
return opf
"""
也可也不自写打开函数
def print_file(path):
f=None
try:
f=open(path, 'r' , encoding='utf-8')
print(f.read())
except Exception as e:
print("异常:",e)
finally:
if f:
f.close()
"""
def print_file(path):
f = openfile(path, 'r')
if f:
print(f.read())
f.close()
def append_file(path, content):
f = openfile(path, 'a')
if f:
f.write(content)
f.close()
test.py测试文件
import my_tools.str_tools
from my_tools import file_tools
a = my_tools.str_tools.str_reverse("uestc")
print(a) # ctseu
print(my_tools.str_tools.str_substr("uestc", 1, 3)) # ues
file_tools.print_file("飞鸟集A.txt") # >︿< 没有该文件,产生了报错: [Errno 2] No such file or directory: '飞鸟集A.txt'
file_tools.print_file("飞鸟集.txt") # 全部打印
file_tools.append_file("飞鸟集.txt", "\nhappy") # 追加happy