如何创建一个函数来打开文件进行写入,并让用户写入文件,当用户写入“stop”时,关闭文件?

2024-07-05 14:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

到目前为止我得到了这个

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

Tags: 文件函数用户文本closedef步骤open
2条回答

首先收集所有的输入,然后用.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

您可以将^{}函数与stop哨兵一起使用,然后将生成的序列字符串与'\n'连接起来输出:

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

相关问题 更多 >