简体   繁体   English

换行到txt文件python

[英]Newline to txt file python

I am trying to create a simple program which asks users for input then puts it into a txt file but my problem is that it's not going into a new row. 我正在尝试创建一个简单的程序,要求用户输入然后将其放入txt文件,但是我的问题是它不会进入新行。

user1=input(ex.Day1)
user2=input(ex.Day2)

The result in my txt file now is 现在我的txt文件中的结果是

Day1Day2

I want to achieve 我想实现

Day1
Day2

in my txt file. 在我的txt文件中。 This is the code that I used. 这是我使用的代码。

fout = open("savedplans.txt", "w")
    fout.writelines(plan_list )
    fout.close()

Please help me and thanks! 请帮助我,谢谢!

You need to do the following: 您需要执行以下操作:

fout.write("\n".join(plan_list))

or 要么

fout.writelines("%s\n" % l for l in plan_list)

You can also use with for file operation: 您还可以将with用于文件操作:

with open("savedplans.txt", "w") as fout:
    fout.write("\n".join(plan_list))
    # fout.writelines("%s\n" % l for l in plan_list)

If plan_list contains the lines to be written, then use this code. 如果plan_list包含要编写的行,则使用此代码。

fi = open("hello.txt","w")
for item in ["Hello","World"]:
    fi.write(item+"\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM