Python-读取和写入用户的输入

发布于 2024-12-18 02:39:33 字数 2104 浏览 0 评论 0原文

我在为我的 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)

我尝试使代码尽可能精简,现在它可以工作了。

由此产生的几个附加问题:

  1. 我需要在最后关闭文件吗?当我尝试关闭 apndn 时,它给了我错误。

  2. 在寻找答案时,我遇到了这个。使用“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:

  1. Do I need to close the file at the end? When I tried to close apnd and n , It gave me errors.

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煮酒 2024-12-25 02:39:33

老实说,您所展示的程序有点混乱。我这样说并不是为了侮辱,而是因为您确实有一个非常清晰的程序需要执行的步骤列表,并且我认为通过废弃现有代码并从头开始,您最终会更好地理解。

在您的问题中,您列出了以下步骤:

  1. 开始时,显示文件以前的所有内容
  2. 使用 while 循环
    1. 接受用户的输入
    2. 如果用户按 Enter 键,则退出程序
    3. 将输入保存到文件
    4. 打印它(注意:您的意思是只打印最新的输入,还是文件中的所有内容?)

将您的整体任务转化为像这样的特定步骤列表可能是编写计算机程序的 80% 的工作。剩下要做的就是将其翻译成代码。因此,我建议您考虑如何单独执行每个步骤。

  • 编写一个代码片段来显示文件的内容
  • 编写一个代码片段来读取用户的一行输入并将其存储在一个变量中
  • 编写一个代码片段来检查变量的内容以查看它是否为空,如果是的话, exit
  • 编写代码片段以将变量的内容追加到文件中
  • 编写代码片段以打印变量(或文件,如果您打算这样做)的内容

这些中的每一个都可以通过一个或多个步骤完成两条线,所以单独地,你应该可以轻松地使用 他们。完成所有部分后,您需要做的就是将它们放在一起:

# display the contents of the file
while True:
    # read a line of input and store it in a variable
    # check the contents of the variable to see if it's empty, and if so, exit
    # append the contents of the variable to the file
    # print the contents of the variable (or of the file)

更新:这不是什么大问题,但您有一个不必要的 if 语句(第二个)在你修改后的计划中。想一想:如果 string_input 为空,Python 将执行 break 语句,该语句立即终止循环。因此,只有当 string_input 不为空时,您才会到达第二个 if 语句。这意味着条件 string_input != "" 在程序中的该点保证为 true,并且无需检查它。

最后我需要关闭文件吗?当我尝试关闭 apndn 时,它给了我错误。

是的,你知道。查看您使用 d 的模式:

# open the file
d = open('user_input.txt', 'a')
# write to it (or read from it)
d.write(string_input + '. ')
# close it
d.close()

每次打开文件时都应该执行相同的操作,即使用 intexttn:打开它,从中读取内容,然后立即关闭它。*

我猜测您遇到错误的原因是您尝试将 .close() 语句位于程序末尾、外部if 语句,甚至可能在 while 循环之外。这会给你一个NameError,因为变量nt在程序中的这些点上没有定义。它们在定义它们的块末尾“过期”。有关这方面的更多信息,请阅读 范围界定。 (维基百科文章可能不是最好的介绍,但您可以搜索 Stack Overflow 和/或网络以获取更多资源。)

在寻找答案时,我遇到了这个。使用“with”语句仍然是最佳实践吗?

是的,with 语句对于 Python 来说相对较新,并且是执行此类“快速”文件 I/O 操作的推荐方法。基本上,with 块负责在最后关闭文件。例如,上面涉及 d 的代码片段相当于

# open the file
with open('user_input.txt', 'a') as d:
    # write to it (or read from it)
    d.write(string_input + '. ')
# Python "automatically" closes it for you

*这种“打开-读/写-关闭”文件访问模式通常好主意。我已经告诉您在程序中使用它,因为学习如何将程序拆分为小步骤并将每个步骤单独转换为代码对您来说很重要。但是,当您编写一个反复将内容写入文件或从文件中读取内容的程序时,有时实际上最好只在开始时打开文件一次并保持打开状态,而不是打开和关闭它每次。如果您好奇,您可以研究的一件事是如何修改程序以减少打开和关闭文件的次数。

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:

  1. Upon starting, display any previous content of the file
  2. Use a while loop to
    1. Accept input from the user
    2. If the user presses Enter, exit the program
    3. Save the input to a file
    4. Print it (note: did you mean to print just the latest input, or everything in the file?)

Turning 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.

  • Write a code snippet to display the contents of a file
  • Write a code snippet to read a line of input from the user and store it in a variable
  • Write a code snippet to check the contents of a variable to see whether it's empty, and if so, exit
  • Write a code snippet to append the contents of a variable to a file
  • Write a code snippet to print the contents of a variable (or of a file, if that's what you meant to do)

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:

# display the contents of the file
while True:
    # read a line of input and store it in a variable
    # check the contents of the variable to see if it's empty, and if so, exit
    # append the contents of the variable to the file
    # print the contents of the variable (or of the file)

Update: This is not a big deal, but you have an unnecessary if statement (the second one) in your revised program. Think about this: if string_input is empty, Python will execute the break statement, which terminates the loop immediately. So you'll only ever reach the second if statement if string_input is not empty. That means the condition string_input != "" is guaranteed to be true at that point in the program, and there's no need to check it.

Do I need to close the file at the end? When I tried to close apnd and n , It gave me errors.

Yes you do. Look at the pattern you used with d:

# open the file
d = open('user_input.txt', 'a')
# write to it (or read from it)
d.write(string_input + '. ')
# close it
d.close()

You should do the same thing every time you open a file, namely with intext, t, and n: 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 the if statement and perhaps even outside of the while loop. That would give you a NameError because the variables n and t 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.)

While looking for answers I came a across, this. Is it still best practice to use a "with" statement?

Yes, the with statement is relatively new to Python and is the recommended way to do "quick" file I/O operations like this. Basically the with block takes care of closing the file at the end. For example, the code snippet above involving d is equivalent to

# open the file
with open('user_input.txt', 'a') as d:
    # write to it (or read from it)
    d.write(string_input + '. ')
# Python "automatically" closes it for you

*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.

_蜘蛛 2024-12-25 02:39:33

使用 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文