import json
1.文本文件相关的
def get_text_file_content(file_path):
"""
获取文本文件的内容
:param file_path:需要获取的文件路径
:return: 文件的内容
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
except FileNotFoundError:
print('Error:文件不存在!!!')
return None
def write_text_file(content, file_path):
"""
将数据写到指定的文本文件中
:param content: 需要写入的内容
:param file_path: 文件路径
:return: 返回写操作是否成功
"""
while True:
try:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
return True
except TypeError:
print('内容必须是字符串')
return False
2.json 文件
1.读操作
def get_json_file_content(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = json.load(f)
return content
except FileNotFoundError:
print('Error: 文件不存在')
return None
2.写操作
def write_json_file(content, file_path):
while True:
try:
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(content, f)
return True
except TypeError:
print('文件格式错误')
return False
3. 二进制文件
1.读操作
def get_binary_file(file_path):
try:
with open(file_path, 'rb') as f:
image_data = f.read()
return image_data
except FileNotFoundError:
print('路径错误')
return None
2.写操作
def write_binary_file(old_file_path,new_file_path):
try:
with open(old_file_path, 'rb') as f:
image_data = f.read()
except FileNotFoundError:
print('路径错误')
return None
with open(new_file_path, 'wb') as f:
new_data = f.write(image_data)
return new_data
if __name__ == '__main__':
# a = write_text_file('123asd', './aaa.text')
# a = get_json_file_content('./aa.json')
# print(a)
# a = write_json_file('123456', './aaa.json')
# a = get_binary_file('./aaa.jpg')
# a = write_binary_file('./aa.jpg', './aaa.png')