【HowToPython】Pythonで「LIST」データを「TXT」ファイルに書き込む方法

Python

Pythonで「LIST」データを「TXT」ファイルに書き込む方法についての記事となっております。

データ構造

### Data Structure

### - SAMPLE
###    - sample.txt
### - output.py 

処理の流れ

実行ファイルの内容

apple
banana
cherry
def option_001(inputList, filePath, solver="N_UpAll"):
    
    info_STR        = "\n".join(inputList)
    write_mode_STR  = \
    {
        "N_UpAll":"w",  ### New / Update All 
        "N":"x",        ### New 
        "UpAll":"w",    ### Update All 
        "UpPlus":"a"    ### Update Append 
    }[solver]

    file_IO =  open(FILE_PATH, mode=write_mode_STR)
    file_IO.write(info_STR)
    file_IO.close()

def option_002(inputList, filePath, solver="N_UpAll"):

    info_STR = "\n".join(inputList)
    write_mode_STR  = \
    {
        "N_UpAll":"w",  ### New / Update All 
        "N":"x",        ### New 
        "UpAll":"w",    ### Update All 
        "UpPlus":"a"    ### Update Append 
    }[solver]

    with open(FILE_PATH, mode=write_mode_STR) as file_IO:
        file_IO.write(info_STR)

### INPUT: File Information (list)
### INPUT: File Path (str)
### OUTPUT: TXT File with Information

STR_LIST = ["apple","banana","cherry"]
FILE_PATH = "sample/output.txt"

option_001(STR_LIST,FILE_PATH)
### option_002(STR_LIST,FILE_PATH)