1. 程式人生 > >用with打開文件

用with打開文件

lac The utf AC undo write python pen AS

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打開文件