[Python]여러파일을 한번에 읽어오기

파이썬에서 여러파일을 한 번에 읽어오는 방법을 알아보자

import os

# 방법1
def read_text_file1(file_path):
    outputs = []
    for file in os.listdir(file_path):        
#         print(file)
        if file.endswith(".txt"):
            target_path = f"{file_path}/{file}"
            
            with open(target_path, 'r') as f:
                outputs.append(f.read().replace('\n', ''))
    return outputs

file_path = "../source/27-1"
print(read_text_file1(file_path))


print()
# 방법2
import glob
def read_text_file2(file_path):
    outputs = list()    
    
    for file in glob.glob(file_path + '/*.txt'):
        with open(file, 'r') as f:
            outputs.append(f.read().strip('\n'))
            
    return outputs


print(read_text_file2(file_path))

## 결과:
['january', 'kibana', 'india', 'hamster', 'lamada', 'zigzag', 'monster', 'orange', 'x-ray', 'yellow', 'notion', 'PHP', 'telegram', 'urban', 'JavaScript', 'world', 'village', 'Python', 'range', 'elite', 'Rust', 'sonic', 'query', 'Solidity', 'Assembly', 'pokemon']

['january', 'kibana', 'india', 'hamster', 'lamada', 'zigzag', 'monster', 'orange', 'x-ray', 'yellow', 'notion', 'PHP', 'telegram', 'urban', 'JavaScript', 'world', 'village', 'Python', 'range', 'elite', 'Rust', 'sonic', 'query', 'Solidity', 'Assembly', 'pokemon']

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다