0
1

More than 3 years have passed since last update.

Python Tips

Last updated at Posted at 2021-05-12

配列の中に含まれるかどうか

hoge.py
        #domain_listが配列 target_domainが変数
        result=target_domain in domain_list

        #配列内にあればTrue
        if result:
            continue

メインプログラムの書き出し

if __name__ == '__main__':」の呪文をつけておくと、外部ファイルからhoge.pyファイルを読み込まれたときに、勝手に実行されない。

hoge.py
if __name__ == '__main__':

乱数を発生する

import random

#0-100の乱数を発生させる
i=random.uniform(0, 100)

#整数化(注意点あり)
seisu=int(i)

フォルダ内のファイル名を取得する

#フォルダ内のファイルパスをすべて取得する
import glob
import os

files = glob.glob("./images/*")

for file in files:
    print(os.path.split(file)[1])

csvの扱い

hoge.py
import csv

#読み込み
with open('data/src/sample.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

#書き込み
with open('data/temp/sample_writer_row.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow([0, 1, 2])
    writer.writerow(['a', 'b', 'c'])

#追記
with open('data/temp/sample_writer_row.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(['X', 'Y', 'Z'])

0
1
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
0
1