teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

修正

2018/05/09 10:02

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -4,20 +4,21 @@
4
4
  ---
5
5
  上書きの場合はちょっと面倒なので、私はだいたい新しいファイルを作ってから置き換えます。
6
6
  ```Python
7
- import os
7
+ from pathlib import Path
8
8
 
9
- src_file = 'test.txt'
9
+ src_file = Path('test.txt')
10
- dst_file = '_dst.tmp'
10
+ dst_file = Path('_work.tmp')
11
11
 
12
- with open(src_file) as fin, \
12
+ with src_file.open() as fin, \
13
- open(dst_file, mode='x') as fout:
13
+ dst_file.open(mode='x') as fout:
14
14
 
15
- fout.write(
15
+ fout.write(
16
- fin.read().replace('テスト', '試み')
16
+ fin.read().replace('テスト', '試み')
17
- )
17
+ )
18
18
 
19
+
19
- os.replace(
20
+ dst_file.replace(
20
- dst_file, src_file
21
+ src_file
21
22
  )
22
23
  ```
23
24