import csv
# This is a list of dictionaries
data = [
{
'meal': 'breakfast',
'units': 20
},
{
'meal': 'lunch',
'units': 40
},
{
'meal': 'dinner',
'units': 50
}
]
# If you wanted the values for lunch, you could do data[1]['units']
# This says access the second value inside the data list,
# and get the value for the units in that dictionary
def write_data(file_path='meals.csv'):
# Open the file for writing without adding extra new lines
# The with syntax will automatically close it for us
with open(file_path, 'w', newline='') as f:
# Create a dictionary writer, telling it what columns to expect
writer = csv.DictWriter(f, ['meal', 'units'])
writer.writeheader()
writer.writerows(data)
def read_data(file_path='meals.csv'):
new_data = []
# open the file for reading
with open(file_path) as f:
# Create a dictionary reader. It will figure things out automagically
reader = csv.DictReader(f)
for row in reader:
print(row)
new_data.append(row)
return new_data
print('writing data...')
write_data()
print('reading data...')
print(read_data())
JSON示例:
import json
data = {
'lunch': 10,
'breakfast': 20,
'dinner': 30
}
def write_data(file_path='meals.json'):
# Open the file for writing without adding extra new lines
# The with syntax will automatically close it for us
with open(file_path, 'w', newline='') as f:
json.dump(data, f)
def read_data(file_path='meals.json'):
# open the file for reading
with open(file_path) as f:
new_data = json.load(f)
return new_data
print('writing data...')
write_data()
print('reading data...')
print(read_data())
import json
data = {
"A": 1,
"B": {"C": 2}
}
# write data to file
with open("file.txt", "w") as file:
file.write(json.dumps(data))
# read data from file
with open("file.txt", "r") as file:
data = json.load(file)
我不完全记得漂亮的印刷品是如何工作的,但这种方式是非常脆弱的。有些东西不按你期望的方式打印的可能性非常高,这可能会破坏现在的状况。你知道吗
我建议使用更标准的数据传输格式,如CSV或JSON。如果你的数据是平面的,我推荐CSV。如果您的数据更复杂,我建议使用JSON。你知道吗
我将用这两种方法的示例来编辑这个答案。你知道吗
CSV示例:
JSON示例:
问题可能是由于没有向文件中添加换行符造成的。一个简单的解决方法是:
f.write(str(meals) + "\n")
但在文本文件中编写代码,然后对其进行评估是个坏主意:
只要在字典中只存储文本、数字和true/false,JSON文件就可以非常清晰地表示它。JSON的优点是它基本上可以被任何编程语言读取:
如果在文件中存储更复杂的对象,可能是类的实例等,那么应该查看pickle。这是另一个内置库,是存储python程序中几乎所有内容的非常方便的方法。正如克劳斯D.在评论中指出的,泡菜并不比你的方法更安全。永远不要从不信任的来源加载pickle对象。你知道吗
这需要:
相关问题 更多 >
编程相关推荐