pyton - テキストファイル

sample

import sys

def read_all_lines(file):
    lines = []

    try:
        f = open(file, 'r', encoding='utf-8')
    except Exception:
        print("open error. not found file:", str(file))
        sys.exit(1)

    for line in f:
        line = line.strip()
        line = line.replace('\n', '')
        lines.append(line)

    f.close()

    return lines


def write_all_lines(file, lines):
    try:
        f = open(file, 'w', encoding='utf-8')
    except:
        print("open error. not found file:", str(file))
        sys.exit(1)

    for line in lines:
        f.write(line + "\n")

    f.close()
import iohelper

outlines = []
outlines.append("aaa")
outlines.append("bbb")
outlines.append("ccc")
iohelper.write_all_lines("./temp/new_file.txt", outlines)


for line in iohelper.read_all_lines("./temp/new_file.txt"):
    print(line)

default

    lines=[]
    with open("test3.txt", "r", encoding="utf8") as file:
        lines = file.readlines()
    lines = []
    for i in range(3):
        lines.append("test1" + str(i))

    with open("test3.txt", "w", encoding="utf8") as file:
        file.writelines("\n".join(lines))