封装文件的读写操作,写操作,写入需要写入文件的内容和地址;读操作,写入需要读取的文件地址。
def get_read(address):
"""
获取文本文件的内容
address:文件地址路径
return:返回文本内容
"""
try:
with open(address, encoding='utf-8') as b:
return b.read()
except FileNotFindError:
print('Error:文件不存在!')
return None
def get_rb(address):
"""
获取文本文件的内容
address:文件地址路径
return:返回文本内容
"""
try:
with open(address, 'rb', encoding='utf-8') as b:
return b.read()
except FileNotFindError:
print('Error:文件不存在!')
return None
def get_write(address, content):
"""
将数据写入文本
content:写入的内容
address:文件路径
return:写入是否成功
"""
try:
with open(address, 'w', encoding='utf-8') as b:
b.write(content)
return print('输入成功')
except TypeError:
print('Error:内容必须是字符串')
def get_wb(address, content):
with open(address, 'wb', encoding='utf-8') as b:
b.write(content)
另一个.py文件
import homework
new_files = homework.get_write('./test1.txt', '这是个测试,mayday')
new_files1 = homework.get_read('./test1.txt')
print(new_files1)
输入成功
这是个测试,mayday