![](/img/trans.png)
[英]Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more?
[英]Input to a seperate file (let the user write text in a python program as it writes to a file)
如何让用户在我的python程序中编写文本,使用打开的“w”将其转换为文件?
我只弄清楚如何使用print将文本写入单独的文档。 但是,如果我想将输入写入文件,它是如何完成的? 简而言之:让用户自己将文本写入单独的文档。
到目前为止,这是我的代码:
def main():
print ("This program let you create your own HTML-page")
name = input("Enter the name for your HTML-page (end it with .html): ")
outfile = open(name, "w")
code = input ("Enter your code here: ")
print ("This is the only thing getting written into the file", file=outfile)
main ()
首先,使用raw_input而不是input。 这样,您可以将文本捕获为字符串,而不是尝试对其进行评估。 但要回答你的问题:
with open(name, 'w') as o:
o.write(code)
您还可以将循环中的代码包围在一直循环中,直到用户点击某个键,如果您希望它们在键入其html文件时能够按Enter键。
编辑:允许连续用户输入的循环示例:
with open(name, 'w') as o:
code = input("blah")
while (code != "exit")
o.write('{0}\n'.format(code))
code = input("blah")
这样,循环将一直运行,直到用户键入“exit”或您选择的任何字符串。 格式行在文件中插入换行符。 我仍然在python2上,所以我不完全确定输入如何处理换行符,但如果包含它,请随意删除格式行并按上述方式使用它。
def main():
print ("This program let you create your own HTML-page")
name = input("Enter the name for your HTML-page (end it with .html): ")
outfile = open(name),'w')
code = input ("Enter your code here: ")
outfile.write(code)
main ()
这不接受多行代码条目。 你需要一个额外的模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.