Python-读取和写入用户的输入
我在为我的 python 课程编写这个短程序时遇到困难,我希望有人可以提供一些帮助。
我想完成什么: 1. 编写一个程序,使用 while 循环接受用户的输入(如果用户按 Enter 键,则退出程序)。 2. 将输入保存到文件,然后打印。 3. 启动后,程序将显示文件的当前内容。
示例:
第一次启动程序。
输入文本:这是输入
这是输入。
输入文本:这是输入的更多文本
。更多文字。
当您第二次启动程序时
这是输入。更多文字。
输入文本:
等等。
到目前为止我所拥有的内容:
intext = open('user_input.txt','a')
intext.close()
string_input = input('Enter text: ')
while True:
open_input = open('user_input.txt','r')
if open_input:
for i in open_input:
print(i)
if string_input != "":
uinput = open('user_input.txt','a')
uinput.write(string_input + '.')
uinput.close()
rd = open('user_input.txt', 'r')
if rd:
for line in rd:
print(line)
if string_input == "":
t = open('user_input.txt', 'r')
for line in t:
print(line)
t.close()
break
问题:打开后,任何以前存储的文本都不会显示。如果用户输入文本,它将无限循环打印,并且不会提示再次输入文本。
优点:输入被记录到文本文件中。如果未输入文本,则退出时任何先前输入的文本都会正确显示。
就像我说的,这是我的家庭作业。我已经寻找答案,但我似乎将代码拆开然后将其重新组合在一起,结果却出现了不同的错误。因此,对此的一些指导将不胜感激。
我忘记提及的一件事是我正在使用 Python 3。
再次感谢 David 帮助我更像程序员一样思考。结果如下:
intext = open('user_input.txt','r').readline()
print(intext)
while True:
string_input = input('Enter text: ')
if string_input == "":
t = open('user_input.txt', 'r').readline()
print(t)
break
if string_input != "":
d = open('user_input.txt', 'a')
d.write(string_input + '. ')
d.close()
n = open('user_input.txt', 'r').readline()
print(n)
我尝试使代码尽可能精简,现在它可以工作了。
由此产生的几个附加问题:
我需要在最后关闭文件吗?当我尝试关闭
apnd
和n
时,它给了我错误。在寻找答案时,我遇到了这个。使用“with”语句仍然是最佳实践吗?
例子:
with open("x.txt") as f:
data = f.read()
do something with data
I am having trouble writing this short program for my python class I was hoping someone could offer some assistance.
What I would like to accomplish:
1. Write a program that uses a while loop to accept input from the user (if the user presses Enter, exit the program).
2. Save the input to a file, then print it.
3. Upon starting, the program will display the current contents of the file.
Example:
Start program for first time.
Enter text: this is input
this is input.
Enter text: some more text
this is input. some more text.
When you start the program for a second time
this is input. some more text.
Enter text:
etc. etc.
What I have so far:
intext = open('user_input.txt','a')
intext.close()
string_input = input('Enter text: ')
while True:
open_input = open('user_input.txt','r')
if open_input:
for i in open_input:
print(i)
if string_input != "":
uinput = open('user_input.txt','a')
uinput.write(string_input + '.')
uinput.close()
rd = open('user_input.txt', 'r')
if rd:
for line in rd:
print(line)
if string_input == "":
t = open('user_input.txt', 'r')
for line in t:
print(line)
t.close()
break
Problems: Upon opening, any previously stored text does not display. If a user inputs text it prints in an infinite loop, and does not prompt to enter text again.
Positives: The input is recorded to the text file. If no text is entered, when exiting any previously entered text does display correctly.
Like I said, this is homework for me. I have searched for the answer, but I seem to be ripping the code apart and putting it back together only to get different errors. So some guidance on this would be greatly appreciated.
One thing I forgot to mention is that I am using Python 3.
Thanks again to David for helping me think more like a programmer. Here are the results:
intext = open('user_input.txt','r').readline()
print(intext)
while True:
string_input = input('Enter text: ')
if string_input == "":
t = open('user_input.txt', 'r').readline()
print(t)
break
if string_input != "":
d = open('user_input.txt', 'a')
d.write(string_input + '. ')
d.close()
n = open('user_input.txt', 'r').readline()
print(n)
I tried to keep the code as slim as possible, and it works now.
A couple questions additional questions that came out of this:
Do I need to close the file at the end? When I tried to close
apnd
andn
, It gave me errors.While looking for answers I came a across, this. Is it still best practice to use a "with" statement?
Example:
with open("x.txt") as f:
data = f.read()
do something with data
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
老实说,您所展示的程序有点混乱。我这样说并不是为了侮辱,而是因为您确实有一个非常清晰的程序需要执行的步骤列表,并且我认为通过废弃现有代码并从头开始,您最终会更好地理解。
在您的问题中,您列出了以下步骤:
while
循环将您的整体任务转化为像这样的特定步骤列表可能是编写计算机程序的 80% 的工作。剩下要做的就是将其翻译成代码。因此,我建议您考虑如何单独执行每个步骤。
这些中的每一个都可以通过一个或多个步骤完成两条线,所以单独地,你应该可以轻松地使用 他们。完成所有部分后,您需要做的就是将它们放在一起:
更新:这不是什么大问题,但您有一个不必要的
if
语句(第二个)在你修改后的计划中。想一想:如果string_input
为空,Python 将执行break
语句,该语句立即终止循环。因此,只有当string_input
不为空时,您才会到达第二个if
语句。这意味着条件string_input != ""
在程序中的该点保证为 true,并且无需检查它。是的,你知道。查看您使用
d
的模式:每次打开文件时都应该执行相同的操作,即使用
intext
、t
和n
:打开它,从中读取内容,然后立即关闭它。*我猜测您遇到错误的原因是您尝试将
.close()
语句位于程序末尾、外部if
语句,甚至可能在while
循环之外。这会给你一个NameError
,因为变量n
和t
在程序中的这些点上没有定义。它们在定义它们的块末尾“过期”。有关这方面的更多信息,请阅读 范围界定。 (维基百科文章可能不是最好的介绍,但您可以搜索 Stack Overflow 和/或网络以获取更多资源。)是的,
with
语句对于 Python 来说相对较新,并且是执行此类“快速”文件 I/O 操作的推荐方法。基本上,with
块负责在最后关闭文件。例如,上面涉及d
的代码片段相当于*这种“打开-读/写-关闭”文件访问模式通常好主意。我已经告诉您在程序中使用它,因为学习如何将程序拆分为小步骤并将每个步骤单独转换为代码对您来说很重要。但是,当您编写一个反复将内容写入文件或从文件中读取内容的程序时,有时实际上最好只在开始时打开文件一次并保持打开状态,而不是打开和关闭它每次。如果您好奇,您可以研究的一件事是如何修改程序以减少打开和关闭文件的次数。
To be honest, your program as you've shown it is kind of a mess. I say this not to be insulting, but because you do have a pretty clear list of the steps your program needs to take, and I think you will wind up with a better understanding by scrapping your existing code and starting from scratch.
In your question, you listed the following steps:
while
loop toTurning your overall task into a list of specific steps like this is probably 80% of the work of writing a computer program. All that's left to do is translate it into code. So I would suggest that you consider how to do each of these steps individually.
Each of these can be done in one or two lines, so individually, you should have an easy time with them. Once you've done all the pieces, all you need to do is put them together:
Update: This is not a big deal, but you have an unnecessary
if
statement (the second one) in your revised program. Think about this: ifstring_input
is empty, Python will execute thebreak
statement, which terminates the loop immediately. So you'll only ever reach the secondif
statement ifstring_input
is not empty. That means the conditionstring_input != ""
is guaranteed to be true at that point in the program, and there's no need to check it.Yes you do. Look at the pattern you used with
d
:You should do the same thing every time you open a file, namely with
intext
,t
, andn
: open it, read from it, and then immediately close it.*I'm guessing that the reason you encountered errors is that you tried to put the
.close()
statements at the end of the program, outside of theif
statement and perhaps even outside of thewhile
loop. That would give you aNameError
because the variablesn
andt
are not defined at those points in the program. They "expire" at the end of the block they are defined in. For more information on this, read up on scoping. (The Wikipedia article is probably not the best introduction, but you can search Stack Overflow and/or the web for more resources.)Yes, the
with
statement is relatively new to Python and is the recommended way to do "quick" file I/O operations like this. Basically thewith
block takes care of closing the file at the end. For example, the code snippet above involvingd
is equivalent to*This "open-read/write-close" pattern of file access is usually a good idea. I've told you to use it in your program because it's important for you to learn how to split a program into small steps and convert each of the steps into code individually. But when you are writing a program that repeatedly writes things out to a file, or reads them in from a file, sometimes it is actually better to just open the file once in the beginning and just keep it open, rather than opening and closing it every time. If you are curious, one thing you could investigate is how to modify your program to reduce the number of times it has to open and close the file.
使用 raw_input 代替 input。
顺便说一句,您忘记在 while 循环中调用输入
,为什么不在程序退出时而不是在每个循环中写入数据呢?
Use raw_input instead of input.
You forget to call input in the while loop
BTW, why not write data just at exit of the program instead of in each loop?