回答編集履歴

2

修正

2019/01/05 07:51

投稿

LouiS0616
LouiS0616

スコア35658

test CHANGED
@@ -30,7 +30,7 @@
30
30
 
31
31
  line = line.replace('\t', ',')
32
32
 
33
- newfile.writelines(line)
33
+ newfile.write(line)
34
34
 
35
35
  ```
36
36
 
@@ -39,3 +39,5 @@
39
39
  - with文を使うなら、生の open/close は不要です。
40
40
 
41
41
  - continueを使うと、『~のときはスキップ』という処理を素直に書けます。
42
+
43
+ - 一行だけ書き出すのなら、writelinesよりwriteの方が自然です。

1

追記

2019/01/05 07:51

投稿

LouiS0616
LouiS0616

スコア35658

test CHANGED
@@ -7,3 +7,35 @@
7
7
  + line = line.replace('\t', ',')
8
8
 
9
9
  ```
10
+
11
+
12
+
13
+ 全体的にも、改善の余地がいくつかあります。とりあえずコード後半だけ。
14
+
15
+ ```Python
16
+
17
+ with open("test2.txt", "r") as oldfile, \
18
+
19
+ open("test3.txt", "w") as newfile:
20
+
21
+
22
+
23
+ for line in oldfile:
24
+
25
+ if any(bad_word in line for bad_word in bad_words):
26
+
27
+ continue
28
+
29
+
30
+
31
+ line = line.replace('\t', ',')
32
+
33
+ newfile.writelines(line)
34
+
35
+ ```
36
+
37
+
38
+
39
+ - with文を使うなら、生の open/close は不要です。
40
+
41
+ - continueを使うと、『~のときはスキップ』という処理を素直に書けます。