ファイルの読み書き

今日やったこと

とりあえずもらったpython スタートブックをやってみた

出てきたエラーを、章ごとにまとめておくう

条件分岐と繰り返し

import random

rand_num=0
while rand_num!=4:
    rand_num=random.randint(0,9)
    print(rand_num)

上のコードを実行したら、IndentationError: expected an intented blockってエラーが出た

これより前にあったブロックが閉じてなかったから、エラーを起こしていた。

あと、IndentationError: unindent does not match any outer indentation levelってエラーも出た。

みてみたら、行のはじめに不必要な半角スペースが入ってたから、それを除いたら直った。

ファイルの読み書き

test_file=open('test.txt','w')
test_file.write('Hello!')
test_file.flush()
test_file.close()

test_file=open('test2.txt','w')
test_file.write('Hello!¥nPython')
test_file.flush()
test_file.close()

上のコードを実行した。でも¥n入れたのに改行されてなかった。。

でも¥n\nに置き換えたらできた。

test_file=open('ikami.csv','r')
for line in test_file:
    test_list=line.strip().split(',')
    print (test_list)

csvファイルも読み書きしてみようと思って、上のコードを実行した。

そしたら、結果がこれ

['\ufeffname', 'id']

['ikami', '2']

['hoge', '234']

['karasawa', '123']

nameの前に'\ufeff'みたいなよくわからんものが入ってきた。

\ufeffって??? - Qiita

調べたらこんな記事があった。調べればなんでも出てくるから便利。

test_file=open('ikami.csv',encoding="utf-8-sig")
for line in test_file:
    test_list=line.strip().split(',')
    print (test_list)

これで実行したら、無事にきれいに出力された。