1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Learn Python In Seminars〜基本的なファイル操作〜

Last updated at Posted at 2021-04-09

読込

./test.txt

2021-04
0  10
1  20
3  30
4  40
5  50

index.py

fileName = "./test.txt"

"""
mode=rは読み出し専用
https://docs.python.org/ja/3/tutorial/inputoutput.html
"""
f = open(fileName, mode="r", encoding="utf-8")

for i in f
    print(i)

↓ 出力結果

2021-04

0  10

1  20

3  30

4  40

5  50

改行を除去

スペースなどが改行として扱われてしまう

for i in f
    s = i.strip()
    print(s)

↓ 出力結果

2021-04
0  10
1  20
3  30
4  40
5  50

タイトルと先頭の数字を削除

for i, o in enumerate(f);
    s = o.strip()
    if i > 0:
       s2 = s.split("\t")
       """
       ex.split後
       [0, 10]
       s2[0]→0、s2[1]→10
       """
       print(s2[1])

↓ 出力結果

10
20
30
40
50

出力

index.py

fileName = "./output.txt"
f = open(fileName, mode="w", encoding="utf-8")

for i in range(5):
    f.write(str(i) + "\n")

"""
closeをしないと更新されない
"""
f.close

↓ 実行

./output.txt

0
1
2
3
4
5

with

withを利用することでcloseを省略可能

with open("./test.txt", mode="r", encoding="utf-8") as f:
    for i in f:
        print(i)

参考


他にも「[Learn Python In Seminar](https://qiita.com/k8m/items/4952894a80c1833e5501)」のシリーズとして書いているので、よければご覧ください!
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?