3
2

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 5 years have passed since last update.

[Python]テキスト処理備忘録

Last updated at Posted at 2019-05-05

コマンドライン引数

  • Pythonのプログラム実行時に,引数を渡すことができる
  • sysモジュールのargvを利用する
  • 入力値は文字列型として扱われる
  • try-exceptは例外処理(ここで考えられる例外は引数が第3引数より少なかった場合の挙動)
import sys
args = sys.argv

try:
	print(args)
	print("第1引数:" + args[1])
	print("第2引数:" + args[2])
	print("第3引数:" + args[3])
except IndexError:
	print("IndexError: list index out of range")

ファイルの読込み

  • UnicodeDecodeError: 'cp932' codec can't decode byte 0xef in position 0: illegal multibyte sequence対策のためUTF-8でファイルをオープンする
  • 引数modeのデフォルト値は'r'なので、省略してもOK
# ファイルをUTF-8でオープンする(,encoding="utf-8")
f = open("test_data.txt", "r",encoding="utf-8")

# 一行ずつ表示する
for line in f:
	print(line)

# ファイルをクローズする
f.close()

ファイルの中身を配列に格納

  • rstripは任意の文字列を右から削除してくれる
# 配列の初期化
Array = []

f = open("list_data.txt", "r",encoding="utf-8")

# 一行ずつ表示する
for line in f:
    Array.append(line.rstrip('\n'))

# ファイルをクローズする
f.close()

print(Array)
3
2
2

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?