# -*- coding:utf8 -*-
"""
# editor: hjjdreamer
# create-time: 2022/12/3-16:57
# Python-Script: chapter9-1-module-example.py
# describe:
"""
import my_utils.str_util
from my_utils import file_util
from my_utils.file_util import append_to_file
print(my_utils.str_util.str_reverse("abcdefg12345678"))
print(my_utils.str_util.substr("abcdefgqreqrwqrqw", 0, 4))
print(my_utils.str_util.substr("abcdefgqreqrwqrqw", 1, 4))
print(my_utils.str_util.substr("abcdefgqreqrwqrqw", 2, 4))
print(my_utils.str_util.substr("abcdefgqreqrwqrqw", 3, 4))
print("\n")
file_util.print_file_info("./data/test_append.txt") # 路径不要搞错
append_to_file("./data/test_append.txt", "qw,2015-06-09,45020,收入,正式")
file_util.print_file_info("./data/test_append.txt")
# create-time: 2022/12/3-16:57
# Python-Script: file_util.py
def print_file_info(file_name):
"""
:func 将给定路径的文件内容输出到控制台中
:param file_name: 即将读取的文件路径
:return: None
"""
# 初始化参数
f = None
# 如果打开文件不存在则会报错
try:
f = open(file_name, "r", encoding="UTF-8")
content = f.read()
print(f"{file_name} content is following")
print(content)
except Exception as e:
print(f"ERROR == REASON == {e}")
finally:
# 如果文件没有,则关闭文件回报错,因此需要添加一个判断
if f:
f.close() # 有文件则关闭
def append_to_file(file_name, data):
"""
:func 将数据追加到指定的文件中
:param file_name: 指定的文件路径
:param data: 指定的数据
:return: None
"""
f = open(file_name, "a", encoding="UTF-8") # append 追加模式,有就追加,没有就创建
f.write(data)
f.write("\n")
f.close()
if __name__ == "__main__":
print_file_info("../data/bill.txt")
print_file_info("../data/bill_computer.txt")
print("\n===test append_to_file function===")
append_to_file("../data/test_append.txt", "name,date,money,type,remarks1")
# -*- coding:utf8 -*-
"""
# create-time: 2022/12/3-16:57
# Python-Script: str_util.py
# describe:
"""
def str_reverse(s):
"""
功能是字符串反转
:param s: 被反转的字符串
:return: 反转后的字符串
"""
return s[::-1] # 字符串反转
def substr(s, x, y):
"""
功能是按照给定的下标完成对字符串的切片
:param s: 将被切片的字符串
:param x: 切片的开始下标
:param y: 切片的结束下标
:return: 切片完成后的字符串
"""
return s[x:y]
if __name__ == "__main__":
print("test str success")
print(str_reverse("abcd1234"))
print("substr test success (substr== abcd1234, 1, 3)")
print(substr("abcd1234", 1, 3))