我昨天发布了一个类似的问题,但没有完全衡量我想要的答复,因为我不够具体。基本上,该函数以.txt文件作为参数,并返回一个字符串,其中所有\n字符都替换为同一行上的“\”。我想不使用WITH来做这个。我以为我做得对,但当我运行它并检查文件时,什么都没有改变。有什么建议吗?你知道吗
我就是这么做的:
def one_line(filename):
wordfile = open(filename)
text_str = wordfile.read().replace("\n", "_")
wordfile.close()
return text_str
one_line("words.txt")
但无济于事。我打开文本文件,它保持不变。你知道吗
文本文件的内容包括:
I like to eat
pancakes every day
应该显示的输出是:
>>> one_line("words.txt")
’I like to eat_pancakes every day_’
你错过了一些步骤。获取更新后的字符串后,需要将其写回文件,下面的示例不使用
with
或者使用
with
Python标准库中的^{} 模块允许您一下子做到这一点。你知道吗
避免
with
语句的要求很简单,但却毫无意义。任何看起来像可以简单地重写为
如果取出
try
/finally
,则会出现一个错误,如果发生错误,handle
就会打开。用于open()
的with
上下文管理器的目的是简化这个常见用例。你知道吗使用^{} 可以通过以下方式实现您想要的:
相关问题 更多 >
编程相关推荐