python - 文件名的名称错误?
问题描述
我正在尝试编写一个将价格分配给列表的程序,但我遇到了麻烦。我不断收到 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")
解决方案
您忘记用引号将文件名括起来。
更改file = open(costlist.txt, "a")
为file = open("costlist.txt", "a")
和
file = open (costlist.txt, "r")
至file = open ("costlist.txt", "r")
推荐阅读
- javascript - 从动态下拉列表中获取选定的值(由 javascript 生成的选项到 ID)
- apache-kafka - 在滚动升级/重启期间,如何检测 kafka 代理何时“完成”?
- nativescript - Nativescript - 卸载框架
- html - 如何匿名从 Swift 中的 URL 获取 HTML 源代码?
- nuxt.js - 错误:更新 nuxt 到 v2.3.4 后的循环依赖
- intellij-idea - 在调试中禁用 PhpStorm 中的 vim 模式
- drools - 是否可以在流口水规则中返回异常?
- angular - 如何使用 *ngFor 和 *ngIf 循环多个 tr
- mysql - 如何在同一日期减去同一列中的两行?
- jenkins - jenkins Nexus 平台插件 3.x 未发生 Nexus 连接