【问题标题】:python - writing to existing filepython - 写入现有文件
【发布时间】:2021-04-11 05:07:08
【问题描述】:

我是编码新手,正在做我的任务,我被困住了。提前致谢。

问题是

writeABFile()

该函数应打开“file.dat”以进行写访问 - 覆盖现有文件

'file'变量中的每一行都需要转换成如下格式的字符串:

8,8,8,8,8,8nl 8 代表椅子,如果椅子可用,则应设置为字符“0”(零),如果椅子已预订,则应设置为字符“1”。 'nl' 是“换行符/回车符”

使用 try 和 except 语句

file.dat 包含列表列表 - [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0 ,0],[0,0,0,0,0,0]]

我的代码是我认为我搞砸了:

def writeABFile():

while not opened:
    try:
        openFile = open("file.dat", "w")

        for row in file:
            openFile.write(",".join(map(str(8,8,8,8,8,8,), row)) + "\n")

        openFile.close()
    except Exception:
        print("Failed to write to file.dat file")
    else:
        openFile.close()

【问题讨论】:

  • 你到底有什么疑问?
  • 我怀疑 openFile.write(",".join(map(str(8,8,8,8,8,8,), row)) + "\n")。它没有做我想要的。

标签: python python-3.x list


【解决方案1】:

提示:您希望从 map(str(8,8,8,8,8,8,), row) 中得到什么?

map 函数接受一个列表和一个函数,并将该函数应用于列表的每个元素。

你的意思是map(row,str)吗?

尝试先将map 构造的结果打印到屏幕上,看看是否是您想要的。

另一个提示,虽然与您的问题无关,但使用 `with`

这让您不必记住关闭它,即使在出现错误的情况下也是如此。

    try:
        with open("file.dat", "w") as openFile:
            for row in file:
                openFile.write("...........\n")
    except Exception:
        print("Failed to write to file.dat file")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2022-11-04
    • 2014-01-18
    相关资源
    最近更新 更多