# 普通文件操作
#1.文本文件相关的操作
def get_txt_file_content(file_path):
"""
获取文本文件的内容
:param file_path: 需要获取的文件路径
:return: 文件内容
"""
try:
with open(file_path,'r',encoding='utf-8') as f:
return f.read()
except:
print('错误:文件不存在')
return None
def write_txt_file(content,file_path):
"""
将数据写到指定的文本文件中
:param content: 写入的内容
:param file_path: 需要获取的文件路径
:return: 返回写操作是否成功
"""
try:
with open(file_path,'w',encoding='utf-8') as f:
f.write(content)
return True
except TypeError:
print('内容必须是字符串')
return False
# 二进制文件操作
def my_open(adress):
with open(adress, 'rb') as f:
print(f.read())
def my_write_bin(adress,contents):
with open(adress,'a') as f:
f.write(contents)
with open(adress, 'rb') as f:
print(f.read())
# json文件操作
def my_open_json(adress):
with open(adress, 'r',encoding='utf-8') as f:
print(f.read())
def my_write_bin(adress,contents):
with open(adress,'a',encoding='utf-8') as f:
w_content = ''
json.dump(w_content, f)
content = json.loads('w_content', encoding='utf-8')
with open(adress, 'r', encoding='utf-8') as f:
print(f.read())
111
import package
package.my_open('./other.txt')
111
Process finished with exit code 0
import package
package.my_write('./other.txt','333')
111333
Process finished with exit code 0