首页 > 解决方案 > 文件名的名称错误?

问题描述

我正在尝试编写一个将价格分配给列表的程序,但我遇到了麻烦。我不断收到 NameError,该成本列表未定义。程序应要求输入,将其附加到列表中,并遍历整个列表,然后将其写入 .txt 文件。

import os
def main():
    if os.path.exists("costlist.txt"):
        os.remove("costlist.txt")

print ("Assignment 6")
print ()
filename = input("Enter a file name, please. Or enter end to end.")
while filename != "end":
    try:
        file = open(filename, "r")
        listie = file.readlines()
        for item in listie:
            print(item)
        break
    except FileNotFoundError:
            filename = input("Sorry, that file wasn't found. Try again?")
    if filename == "end":
        exit
file.close()
listie.sort()
file = open(filename, "w")
for item in listie:
   file.write(item.strip("\n"))
file.close()
for item in listie:
    cost = input(print( item + "should cost how much?"))
    try:
        float.cost
    except ValueError:
            print ("You entered an invalid float that can't convert string to float:" + cost)
            print ("Skipping to the next item after" + item)
    print (item + "has a cost of" + cost + "dollars")
    file = open(costlist.txt, "a")
    file.append(cost)
print ("Cost List")
file = open (costlist.txt, "r")
for item in file:
    print (item)
print ("Program End")

标签: pythonlistio

解决方案


您忘记用引号将文件名括起来。

更改file = open(costlist.txt, "a")file = open("costlist.txt", "a")

file = open (costlist.txt, "r")file = open ("costlist.txt", "r")


推荐阅读