Python 뿌시기

[NBcamp Python] ETC 파일 입출력 (glob, os, Split & Join)

pjw250 2024. 10. 19. 17:53

# glob 함수를 이용한 파일 찾기

# 현재 경로의 모든 파일을 찾기
file_list1 = glob.glob('*')
# 단일 파일 패턴으로 파일을 찾기
file_list2 = glob.glob('drive')
# 디렉토리 안의 모든 파일 찾기
file_list3 = glob.glob('sample_data/*')
# 특정 확장자를 가진 파일만 찾기
file_list4 = glob.glob('sample_data/*.csv')

 

# import os 를 이용한 파일/폴더 생성, 삭제, 경로 추출

# 현재 작업 디렉토리 추출 (current working directory)
import os
cwd = os.getcwd()
print(cwd)
# 디렉토리 생성 / 폴더
import os
os.mkdir('sample_data/new_directory')
# 폴더/파일 명 변경
import os
os.rename('sample_data/new_directory', 'sample_data/new_directory2')
# 폴더/파일 삭제 1
import os
os.remove(file_adress)
# 폴더/파일 삭제 2
import os
os.remove('sample_data/data.csv')
# 경로의 폴더/파일 조회 
import os
files = os.listdir('/content')
print(files)
# 경로 출력 (join)
import os
path = os.path.join('/content', 'sample_data', 'mnist_test.csv')
print(path)

 

# Split과 Join

sentence = "Hello, how are you doing today?"
words = sentence.split()
print(words)  # 출력: ['Hello,', 'how', 'are', 'you', 'doing', 'today?']

data = "apple,banana,grape,orange"
fruits = data.split(',')
print(fruits)  # 출력: ['apple', 'banana', 'grape', 'orange']

text = """First line
Second line
Third line"""
lines = text.split('\n')
print(lines)  # 출력: ['First line', 'Second line', 'Third line']

words = ['Hello,', 'how', 'are', 'you', 'doing', 'today?']
sentence = ' '.join(words)
print(sentence)  # 출력: Hello, how are you doing today?

fruits = ['apple', 'banana', 'grape', 'orange']
data = ','.join(fruits)
print(data)  # 출력: apple,banana,grape,orange

sentence = "Hello, how are you doing today?"
words = sentence.split()
first_three_words = words[:3]
print(first_three_words)  # 출력: ['Hello,', 'how', 'are']

text = "   Hello   how   are   you   "
cleaned_text = text.strip()
words = cleaned_text.split()
print(words)  # 출력: ['Hello', 'how', 'are', 'you']

 

# Split 과 Join을 이용한 데이터의 경로 표현

# 데이터의 경로를 문자열로 표현
file_path = "/usr/local/data/sample.txt"

# split() 함수를 사용하여 디렉토리와 파일명으로 분할
directory, filename = file_path.rsplit('/', 1)
print("디렉토리:", directory)  # 출력: 디렉토리: /usr/local/data
print("파일명:", filename)    # 출력: 파일명: sample.txt