文本文件读写
import os
"""
常用方法
文件读:readlines()
文件写:write()
"""
df = open('demo1.txt', mode='r')
df_name = df.name
df.close()
with open('demo1.txt', 'r') as df:
readlines_df = df.readlines()
print('-------')
for line in readlines_df:
print(line)
print('-------')
with open('demo1.txt', 'a') as df:
df.write("增加一行。")
df.write("\n")
df.write("增加第二行。")
df.write("\n")
tag = os.path.exists("text_file.py")
print(tag)
json文件读写
import json
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'A': 1, 'B': 2, 'C': 3}
dict3 = {'q': 1, 'b': 2, 'z': 3}
'''
读写多个字典,用enumerate将字典存入字典
'''
all_dict = dict(enumerate(dict_list))
with open('demo2.json', 'w') as f:
json.dump(all_dict, f)
with open('demo2.json', 'r') as f:
dd = json.loads(f.read())
print(dd)
'''
读写多个字典,将字典存入list
'''
dict_list = []
dict_list.append(dict1)
dict_list.append(dict2)
dict_list.append(dict3)
with open('demo3.json', mode='w', encoding='utf-8') as f:
json.dump(dict_list, f)
with open('demo3.json', mode='r', encoding='utf-8') as f:
dicts = json.load(f)
for d in dicts:
print(d)
表格数据读写