![](/img/trans.png)
[英]Can't open file: "NameError: name <filename> is not defined"
[英]NameError for filename?
我正在嘗試編寫一個將價格分配給列表的程序,但我遇到了麻煩。 我不斷收到 NameError,該成本列表未定義。 程序應要求輸入,append 將其寫入列表,go 通過整個列表,然后將其寫入.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")
您忘記用引號將文件名括起來。
file = open(costlist.txt, "a")
更改為file = open("costlist.txt", "a")
和
file = open (costlist.txt, "r")
到file = open ("costlist.txt", "r")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.