简体   繁体   English

如何使用新行将内容写入具有多个输入的文本文件?

[英]how to write a content to the text file with multiple inputs with new line?

I have a text file already but it has no content.我已经有一个文本文件,但它没有内容。 I want save my inputs in text file and overwrite it instantly if the program reruns.我想将我的输入保存在文本文件中,并在程序重新运行时立即覆盖它。 Here is my code这是我的代码

for i in range(0,15):
    ele = input(str(i + 1) + ". ")
    f = open('filename', 'w')
    f.write("%s\n" %(ele))
    f = open('filename', "a")

The only input that is saving is the last one.唯一保存的输入是最后一个。

For example:例如:

  1. A一种
  2. B
  3. C C
  4. D D
  5. E

..... 15. Z ..... 15. Z

The only input that is saving is the Z and changed if the user rerun the program唯一保存的输入是 Z 并在用户重新运行程序时更改

This is happening because you're opening file in 'w' mode also, inside the for loop, which is replacing the contents before append can save you from this.发生这种情况是因为您也在 for 循环内以 'w' 模式打开文件,它会在 append 之前替换内容,从而避免这种情况。

Do this instead:改为这样做:

for i in range(15):
    mode = 'w' if i==0 else 'a'
    ele = input(str(i + 1) + ". ")
    f = open('filename', mode)
    f.write("%s\n" %(ele))

This program will rewrite the file when program reruns, else it'll append.该程序将在程序重新运行时重写该文件,否则它将附加。

According to your comment query, please find the solution below.根据您的评论查询,请在下面找到解决方案。

S, delimiter = "", " "                      # Set the delimiter value as per your convenience

for i in range(3):
    S += input(str(i + 1) + ". ") + delimiter

f = open('filename', 'w')
f.write(S)

To Reduce Code Size and to Increase Speed, you can use List Comprehension and Chaining要减少代码大小并提高速度,您可以使用列表理解和链接

#    Replace " ".join... with delimiter.join...
S = " ".join([input(str(i + 1) + ". ") for i in range(3)]) # List Comprehension
open('filename', 'w').write(S) # Chaining

each time you open the file as w , it will rewrite the whole content, as @Dani Mesejo said, you should open your file before the for loop like this:每次您以w打开文件时,它都会重写整个内容,正如@Dani Mesejo 所说,您应该在 for 循环之前打开您的文件,如下所示:

f = open('filename', 'w')
for i in range(0,15):
    ele = input(str(i + 1) + ". ")        
    f.write("%s\n" %(ele))
f.close()

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

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