如果Python中没有语法错误,则无法将字典保存到.txt文件

2024-04-24 22:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

我不完全记得漂亮的印刷品是如何工作的,但这种方式是非常脆弱的。有些东西不按你期望的方式打印的可能性非常高,这可能会破坏现在的状况。你知道吗

我建议使用更标准的数据传输格式,如CSV或JSON。如果你的数据是平面的,我推荐CSV。如果您的数据更复杂,我建议使用JSON。你知道吗

我将用这两种方法的示例来编辑这个答案。你知道吗

CSV示例:

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())

问题可能是由于没有向文件中添加换行符造成的。一个简单的解决方法是:f.write(str(meals) + "\n")

但在文本文件中编写代码,然后对其进行评估是个坏主意:

  • 只有python程序才能读取该文件
  • 它很容易出现语法错误(就像你的问题一样)
  • 这很不安全。恶意代码可能会出现在您的文件中。你知道吗

只要在字典中只存储文本、数字和true/false,JSON文件就可以非常清晰地表示它。JSON的优点是它基本上可以被任何编程语言读取:

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)

如果在文件中存储更复杂的对象,可能是类的实例等,那么应该查看pickle。这是另一个内置库,是存储python程序中几乎所有内容的非常方便的方法。正如克劳斯D.在评论中指出的,泡菜并不比你的方法更安全。永远不要从不信任的来源加载pickle对象。你知道吗

import pickle

with open("file.txt", "wb") as file:
    pickle.dump(data, file)

with open("file.txt", "rb") as file:
    data = pickle.load(file)

这需要:

import pprint
import time
import os
pretty = pprint.PrettyPrinter(width = 20)
meals = {}
command = ""
condition = False
n = False
if not os.path.isfile('meals.txt'):
    f = open("meals.txt", "w+")
    f.write(str(meals))
    f.close()
else:
    n = True

def save_dict_to_file(meals):
    f = open("meals.txt", "w+")
    f.write(str(meals))
    f.close()

def load_dict_from_file():
    f = open("meals.txt", "r+")
    data = f.read()
    f.close()
    return eval(data)
if n:
    meals = load_dict_from_file()

def add_entry():
    meal = input("Enter name of meal: ").lower()
    units = int(input("Enter units needed: "))
    meals[meal] = units
    pretty.pprint(meals)
    save_dict_to_file(meals)
import os
def remove_entry():
    os.remove('meals.txt')

def help():
    pretty.pprint('help')

def view_dict():
    pretty.pprint(load_dict_from_file())

def ending_message():
    pretty.pprint('done')

while True:
    command = input("> ").lower()
    if command == "help":
        help()
    elif command == "add":
        add_entry()
    elif command == "exit":
        save_dict_to_file(meals)
        ending_message()
        time.sleep(3)
        break
    elif command == "remove":
        remove_entry()
    elif command == "view":
        view_dict()

相关问题 更多 >