【问题标题】:How do I make a function that opens the file for writing and let the user write to the file, and when the user write "stop", close the file?如何创建一个打开文件进行写入并让用户写入文件的功能,当用户写入“停止”时,关闭文件?
【发布时间】:2019-03-20 02:18:10
【问题描述】:

如何创建一个函数,1. 打开一个文件进行写入,2. 让用户在 while 循环中写入文本,使用 ("\n") 向用户写入 "stop",继续换行,然后循环转到步骤 3。关闭文件。

到目前为止,我得到了这个

def writesomething(filename):
    file1=open("randomfile","w")
    file1.write("")
    file1.close()

【问题讨论】:

  • 您承认在第 2 步中需要 while 循环;你的代码中的循环在哪里?
  • 是的,这是我的问题之一。
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask... the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。但是,如果您遵循您在网上找到的任何资源,进行诚实的编码尝试并遇到问题,那么您将有一个很好的示例可以发布。

标签: python python-3.x file


【解决方案1】:

首先收集所有的输入,然后用\n.join()它,然后一次性写出来。

text = []
user = input('Enter text to write to file (\'quit\') to end: ')
text.append(user)
while user != 'quit':
    user = input('Enter text to write to file (\'quit\') to end: ')
    text.append(user)
res = '\n'.join(text)
with open('text.txt', 'w') as f:
    f.write(res)
Enter text to write to file ('quit') to end: vash
Enter text to write to file ('quit') to end: the
Enter text to write to file ('quit') to end: stampede
Enter text to write to file ('quit') to end: quit
chrx@chrx:~/python/stackoverflow/10.11$ cat text.txt
vash
the
stampede

【讨论】:

    【解决方案2】:

    您可以将iter 函数与stop 的标记一起使用,然后将生成的序列字符串与'\n' 连接以进行输出:

    with open('randomfile', 'w') as f:
        f.write('\n'.join(iter(input, 'stop')))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2017-08-26
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      相关资源
      最近更新 更多