수업정리/Fundamental

Python basic 6 - os.path, glob(), str, file.read() readlines() write() writelines()

GreenBNN 2023. 4. 19. 14:32

os.path 를 이용해서 파이썬 안에서 파일이 있는지, 파일들의 이름을 받을 수 있다.

os.path.isabs(_path): 경로가 절대 경로인 경우 True를 반환합니다.
os.path.isdir(_path): 경로가 존재하는 디렉토리인 경우 True를 반환합니다.
os.path.isfile(_path): 경로가 존재하는 파일인 경우 True를 반환합니다.
os.path.exists(_path): 경로가 존재하는 경우 True를 반환합니다.
os.path.basename(_path): 경로의 기본 파일 이름을 반환합니다.
os.path.dirname(_path): 경로의 디렉토리 이름을 반환합니다.
os.path.join(_path, filename): 파일 이름과 디렉토리 이름을 지능적으로 결합한 경로를 반환합니다

 

 

glob() 와 os.path 사용하기

glob() 은 파이썬 안에서 파일 경로명을 다룰 때 유용하게 사용된다.

import glob

files = glob.glob('*.txt')

print(files)

for a_file in files:
    readin = open(a_file).read()
    print(readin)

위 코드는 현재 디렉토리에서 .txt 파일을 모두 모아서 각각을 읽는 코드이다.

 

import glob
fns = glob.glob('/home/jek/cs4ks/data') # 그냥 dir 리턴
fns = glob.glob('/home/jek/cs4ks/data/*') # dir 안에 모든 파일 리턴
fns = glob.glob('/home/jek/cs4ks/data/*.txt') # dir 안에 .txt 파일 리턴
fns = glob.glob('/home/jek/cs4ks/data/?.txt') # dir 안에 ? 글자 만큼 .txt 파일 리턴


fns = glob.glob('*') # 현재 디렉토리 모든 파일 읽기
fns = glob.glob('hello*.py') # 현재 디렉토리에 앞이 hello면 뒤 상관없이 다 읽기

* : 모든 파일 읽기

*.txt : 확장자 지정, 이름 상관 없이 모든 파일 읽기

??.txt : 확장자 지정, ? 개수 만큼 파일 이름 길이 파일 읽기

 

fns = glob.glob('data/*[0-9].txt') # 파일 이름 상관 없고 뒤에 숫자 달린 .txt 파일 리턴
fns = glob.glob('data/*[0-9]*') # 파일 이름 상관 없고 뒤에 숫자 달린 모든 파일 리턴
fns = glob.glob('data/*.*') # 그냥 모든 파일 리턴
fns = glob.glob('data/??[0-9].*') # 2글자 뒤에 숫자 달린 모든 파일 리턴

[0-9] : 숫자가 있는 파일

 

import file

'r' 모드 파일: 기본값으로, 읽기 모드로 파일을 엽니다.
str = file.read(): 파일의 전체 내용을 문자열로 읽어옵니다.
file.readlines(): 파일의 각 줄을 리스트의 요소로 읽어옵니다.


'w' 모드 파일: 쓰기 모드로 파일을 엽니다.
file.write(string): 문자열을 파일에 씁니다. 쓴 문자의 수를 반환합니다.
file.writelines(list): 문자열의 리스트를 파일에 씁니다.

 

str : 문자열 처리 함수

str.split(symbol): 문자열을 symbol 기준으로 나누어 리스트에 저장
str.find(string, index): 문자열 string을 index부터 str 에서 찾아 첫번째 시작 위치를 반환
str.join(list): 리스트를 문자열로 합쳐서 반환

 

'at %d from [%s]' % (pos, data) : 문자열을 이런 식으로 변환 %d 에는 pos 가 들어가고 %s 에는 data들어감

'at {} from [{}]'.format(pos, data) : 위와 똑같음

f'{pos} at [{data}]' : 위와 동일

 

glob_file_str.py

 #coding utf-8

 import glob

 fns = glob.glob('*.py') # .py 파일 모두 읽기
 ofile = open('print_in_py.list','w',encoding='utf-8')
 all_lines = []
 for fn in fns:# 모든 파일에 대해
     with open(fn) as infile: # fn 파일을 열어서 infile 이라고 지정
         lines = infile.readlines() # 파일 읽기
         w_lines = []
         for line in lines: # 각 줄에 대해서 형식에 맞춰서 출력하기
             pos = line.find('print')
             w_lines.append(f'print {pos} at {line}')
         print(w_lines)
         all_lines.extend(w_lines) # 이 줄들 저장하기
 ofile.writelines(all_lines) # 파일 쓰기
 ofile.close()