用with打开文件

Posted PAYNE1Z

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用with打开文件相关的知识,希望对你有一定的参考价值。

rep_word = ‘The piece is gone, left the puzzle undone‘

# \ 换行,跟shell一样
with open(‘nothing‘, ‘r‘, encoding=‘utf-8‘) as f,     open(‘nothing1‘, ‘w‘, encoding=‘utf-8‘) as f_new:
        for line in f:
            if rep_word in line:
                line = line.replace(rep_word, ‘碎片散去,留下已解的迷‘)
            f_new.write(line)


# 运行前 nothing
# Trying hard to fill the emptiness
# The piece is gone, left the puzzle undone
# Ain‘t that the way it is

# 运行后 nothing1
# Trying hard to fill the emptiness
# 碎片散去,留下已解的迷
# Ain‘t that the way it is

  

以上是关于用with打开文件的主要内容,如果未能解决你的问题,请参考以下文章

Python中open和with open有什么区别?怎么用?

用with来打开文本文件

用with打开文件

Nginx——Nginx启动报错Job for nginx.service failed because the control process exited with error code(代码片段

如何包装所有片段(不在里面)or) with?

[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段