读写txt文件
with open("../files/test.txt", encoding="utf-8-sig") as f:
str = f.read()
lst = []
if str:
data = str.split("\n")
for row in data:
if len(row) > 0:
lst.append(row.split(","))
print(lst)
with open("../files/test.txt", "w", encoding="utf-8-sig") as f:
str = ""
for row in lst:
str += ",".join(row) + "\n"
if len(str) > 0:
f.write(str)
读写json文件
import json
obj = [[1, 2], 123, 123.123, "abc", {"key2": (4, 5), "key1": (1, 2)}]
print(obj) # [[1, 2], 123, 123.123, 'abc', {'key2': (4, 5), 'key1': (1, 2)}]
# 编码 转化成str格式
encoded_json = json.dumps(obj)
print(encoded_json) # [[1, 2], 123, 123.123, "abc", {"key2": [4, 5], "key1": [1, 2]}]
print(type(encoded_json)) # <class 'str'>
encoded_json = json.dumps(obj, sort_keys=True) # 对dict对象进行排序
print(encoded_json) # [[1, 2], 123, 123.123, "abc", {"key1": [1, 2], "key2": [4, 5]}]
encoded_json = json.dumps(obj, indent=4) # 缩进,便于阅读
print(encoded_json)
# 解码 将str转化成dict/list格式
decoded_json = json.loads(encoded_json)
print(decoded_json) # [[1, 2], 123, 123.123, 'abc', {'key2': [4, 5], 'key1': [1, 2]}]
with open("../source-files/test.json", encoding="utf-8-sig") as fp:
data = json.load(fp)
print(data) # {'name': '一', 'age': 5, 'area': 'a'}
with open("../source-files/test.json", "w+", encoding="utf-8-sig") as fp:
if len(data) > 0 and "data" in data and "name" in data["data"]:
data["data"]["name"] = "二"
json.dump(data, fp)
读写csv
import csv, random
data = []
with open("../files/pd.csv", encoding="utf-8-sig") as f:
reader = csv.reader(f, skipinitialspace=True)
headers = next(reader)
for row in reader:
data.append(row)
print(headers, data)
with open("../files/pd.csv", "w", newline="\n") as f:
writer = csv.writer(f)
data.append(
[
len(data),
random.randint(5, 10),
random.randint(2, 8),
random.randint(6, 15),
random.randint(1, 20),
]
)
writer.writerows([headers])
writer.writerows(data)
f.close()