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

回答編集履歴

2

Fix answer

2020/07/02 12:38

投稿

y_shinoda
y_shinoda

スコア3272

answer CHANGED
@@ -13,14 +13,6 @@
13
13
  print(line)
14
14
  ```
15
15
 
16
- test.txt:
17
-
18
- ```text
19
- 1行目
20
- 2行目
21
- 3行目
22
- ```
23
-
24
16
  実行結果:
25
17
 
26
18
  ```python

1

Update answer

2020/07/02 12:38

投稿

y_shinoda
y_shinoda

スコア3272

answer CHANGED
@@ -1,14 +1,15 @@
1
1
  次のようにします:
2
2
 
3
3
  ```python
4
- def read_by_line_number(path_to_file, number):
4
+ def read_by_line_number(string, line_number):
5
- with open(path_to_file) as fp:
6
- for i, line in enumerate(fp):
5
+ return s.splitlines()[line_number - 1]
7
- if i == number - 1:
8
- return line
9
- raise Exception()
10
6
 
7
+
8
+ s = """1行目
9
+ 2行目
10
+ 3行目"""
11
+
11
- line = read_by_line_number('test.txt', 2)
12
+ line = read_by_line_number(s, 2)
12
13
  print(line)
13
14
  ```
14
15