鱼C论坛

 找回密码
 立即注册
查看: 2206|回复: 3

[已解决]【第29讲课后作业】 为什么不能用列表配合writelines?

[复制链接]
发表于 2020-2-20 17:36:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. def new_txt(file_name):
  2.     file = open(file_name, "w")
  3.     #txt = []
  4.     print("请输入文本内容【单独输入:w 保存退出】")
  5.    
  6.     while 1:
  7.         poem = input()
  8.         if poem != ":w":
  9.             #txt.append[poem]
  10.             file.write("%s\n" %poem)
  11.             #这里就是file.writelines(txt)
  12.             continue
  13.         else:
  14.             break
  15.     file.close()
  16.    
  17. file_name = input("请输入文件名:")
  18. new_txt(file_name)
复制代码


如上,#后面是我本来的思路,为什么不能先把输入的字符串append进列表,然后配合writelines?

另,如果输入多行内容而不是像上述一行一行输入,该如何改动?
最佳答案
2020-2-20 17:47:31
确实可以那样搞,改成这样:

  1. def new_txt(file_name):
  2.     file = open(file_name, "w")
  3.     txt = []
  4.     print("请输入文本内容【单独输入:w 保存退出】")
  5.    
  6.     while 1:
  7.         poem = input()
  8.         if poem != ":w":
  9.             txt.append(poem+"\n")    # 修改
  10.             file.writelines(txt)
  11.             continue
  12.         else:
  13.             break
  14.     file.close()
  15.    
  16. file_name = input("请输入文件名:")
  17. new_txt(file_name)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-20 17:47:31 | 显示全部楼层    本楼为最佳答案   
确实可以那样搞,改成这样:

  1. def new_txt(file_name):
  2.     file = open(file_name, "w")
  3.     txt = []
  4.     print("请输入文本内容【单独输入:w 保存退出】")
  5.    
  6.     while 1:
  7.         poem = input()
  8.         if poem != ":w":
  9.             txt.append(poem+"\n")    # 修改
  10.             file.writelines(txt)
  11.             continue
  12.         else:
  13.             break
  14.     file.close()
  15.    
  16. file_name = input("请输入文件名:")
  17. new_txt(file_name)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2020-2-20 18:03:51 | 显示全部楼层
一个账号 发表于 2020-2-20 17:47
确实可以那样搞,改成这样:

感谢!!
另,我刚运行了一下发现
  1. file.writelines(txt)
复制代码

这一行应该拿到 while循环外面,不然就会重复添加
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-20 18:05:12 | 显示全部楼层
xiaofan1228 发表于 2020-2-20 18:03
感谢!!
另,我刚运行了一下发现
这一行应该拿到 while循环外面,不然就会重复添加

不会的,input() 会堵塞线程。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-3 07:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表