gpt4 book ai didi

python - 如何创建从 raw_input 创建的字典/列表/类

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:42 24 4
gpt4 key购买 nike

我对 python 很陌生,我正在尝试制作一个非常基本的虚拟机,能够制作和读取“文本文件”(格式化字符串)。

现在,将有一个命令允许用户创建文件。该文件存储为一个类,但我不确定如何做这样的事情 -

def filecreate(filename,contents):
filename = contents
filecreate(str(raw_input("File Name: ")), insertcontenthere)

在尝试在idle/pycharm中做类似的事情时,你不能,因为它会因为文件名未定义而对你大喊大叫。

我已经研究了构造函数,但我不知所措。答案可能很明显,我没有看到它,但我找不到它。

(它可能已经得到解答,但由于措辞,我无法准确搜索它。)

最佳答案

您必须以某种方式创建一个文件系统。如果我可以建议的话:

class FileSystem(dict):
# I'm not really sure what you need a file system
# to do specifically. Probably things like
# FileSystem.listdir but this is kind of beyond the
# scope of this question

fs = FileSystem()

def filecreate(filename,contents):
global fs
fs[filename] = contents

filecreate(str(raw_input("File Name: ")), insertcontenthere)

将这一切实现到 FileSystem 中可能不是一个坏主意,因此您将调用 fs.filecreate(raw_input(), content)。此外,您永远不需要在 raw_input 上调用 str ——它总是返回一个字符串。

关于python - 如何创建从 raw_input 创建的字典/列表/类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com