如何将6条target.write命令合并为单条(《笨办法学Python3.6》)
解决《笨办法学Python》中合并多条
target.write命令的问题 嘿,我太熟悉这个练习了!把6条target.write()合并成单条命令其实就是在练字符串的多行处理和格式化,我来一步步帮你搞定~
首先,先明确书里那6条原始的target.write命令大概是这样的(你没贴全,但根据练习16的内容,应该是类似下面的写法):
target.write("First line I want to write.\n") target.write("Second line right here.\n") target.write("Third line coming up.\n") target.write("Fourth line, keep going.\n") target.write("Fifth line almost there.\n") target.write("Sixth line, done!\n")
方法1:用三重引号的多行字符串(最直观推荐)
Python的三重引号("""或''')允许你直接写跨多行的字符串,自动保留换行,完全不需要手动加\n转义,完美适配这个需求:
from sys import argv script, filename = argv print(f"We're going to erase {filename}") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") input("?") print("O...") print("Opening the file...") target = open(filename, 'w') # 这里就是合并后的单条write命令! target.write("""First line I want to write. Second line right here. Third line coming up. Fourth line, keep going. Fifth line almost there. Sixth line, done! """) print("Closing the file.") target.close()
方法2:用换行符\n拼接成单字符串
如果你想用转义的方式实现,也可以把所有内容放在一个字符串里,用\n分隔每一行,效果和上面一样:
target.write("First line I want to write.\nSecond line right here.\nThird line coming up.\nFourth line, keep going.\nFifth line almost there.\nSixth line, done!\n")
为什么这样能行?
- 三重引号字符串会把你输入的每一行内容(包括换行)原封不动地保留,所以写入文件后和原来6条
write的效果完全一致。 - 用
\n转义的方式则是手动告诉Python哪里需要换行,本质和原来每条命令加\n是一样的,只是合并成了一次写入。
记得运行前确认你确实想清空目标文件哦,因为open(filename, 'w')模式会直接覆盖原有内容~
内容的提问来源于stack exchange,提问作者Matt Hathaway
相关产品推荐
相关产品推荐

