python - 来人解释一下为什么这段代码对我不起作用?
问题描述
我有我正在编写的这个程序,它应该只使用一个。需要使用 for 来询问名称和分数是什么。此外,需要 for 将分数和名称写入文件。尝试运行它时出现错误提示“UnsupportedOperation: Not Readable”
Golf_File = open('golf.txt', 'w')
names = []
scores = []
for line in Golf_File:
input("Please enter a players name: ")
if name !='':
break
score = input("Please input the players score: ")
if name != '' and score !="":
golf.txt.write(name + "\n")(str(score) + "\n")
Golf_File.close()
EDIT =
for line in Golf_File:
Golf_File = open('golf.txt', 'w')
names = input("Please enter a players name: ")
score = input("Please input the players score: ")
Golf_File.write(str(names) + "\n")
Golf_File.write(str(scores) + "\n")
Golf_File.close()
解决方案
在您的回答中,您使用“w”打开了 Golf_File,这意味着在您想要读取文件时写入。要读取文件使用“r”而不是“w”又名
Golf_File = open('golf.txt', 'r')
for line in Golf_File:
Golf_File = open('golf.txt', 'w')
names = input("Please enter a players name: ")
score = input("Please input the players score: ")
Golf_File.write(str(names) + "\n")
Golf_File.write(str(score) + "\n")
Golf_File.close()
我不是 100% 确定这可行,因为我不知道 golf.txt 里面有什么,但希望这可以帮助你。如有错误欢迎指正:)。我进行了一些编辑,例如更改错误的变量名称并将“r”(读取)更改为“wr”(写入和读取)。还要在循环之后关闭文件,这样它就可以工作不止一次。我以为 wr 是一回事,但我错了
推荐阅读
- python-3.x - 浏览器上的错误 404 未显示静态文件夹文件
- chart.js - Chartkick 高度始终为固定大小,即使响应式 true
- javascript - 高质量的画布drawImage - Javascript
- java - Spring swagger2:如何设置 HTTPS 协议?
- postgresql - 计算2点之间的距离(大约)
- python - input contains NaN when i'm trying to train model
- ssis - SSIS Delete files from folder based on a selection from SQL Database
- node.js - Express and Node.js low performance when other route is in heavy work
- javascript - Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters; using Nodejs and Express server
- r - 将标签放在 ggplot 的顶部