Python

파이썬 - 파일, 디렉토리

kakaroo 2023. 3. 7. 07:25
반응형

파일의 경로

file = "/content/drive/A/letter.txt"

dirname = os.path.dirname(file)

basename = os.path.basename(file)

print(f'dirname = {dirname}')

print(f'basename = {basename}')

 

f-string 포매팅은 파이썬 버전 3.6 부터 사용할 수 있는 따끈따끈한 기능 입니다.
이전에 언급했던, %포매팅과 str.format 방법보다 더 최근에 나온 것 입니다.

f-string의 모양은 f와 {}만 알면 됩니다. 문자열 맨 앞에 f를 붙여주고, 중괄호 안에 직접 변수 이름이나 출력하고 싶은것을 바로 넣으면 됩니다.
f'문자열 {변수} 문자열'

 

 

디렉토리/파일 확인

 

현재 작업디렉토리

os.getcwd()

 

os.cdir('./MyDir/A')

os.mkdir('../C')

os.path.isdir(filename)

os.path.isdir(filename)

os.path.exists(filename)

 

 

파일 읽기 쓰기

 

예)

 

with 구문을 사용하면 statement 를 벗어날 때 자동적으로 반환되므로 close 를 사용할 필요가 없다.

 

 

오류 발생시 try except 를 사용하자

 

파일 복사

import os

print(os.getcwd())

fileR = 'D:/data/python/workspace/class/test.txt'
fileW = 'D:/data/python/workspace/class/test_cp.txt'

if os.access(fileR, os.F_OK) and os.access(fileR, os.R_OK) :
    with open(fileR, 'r') as rp, open(fileW, 'w') as wp :
        msg = rp.read()
        wp.write(msg)
    print(f'{fileR!r} copy success')
else :
    open(fileR, 'w')

 

 

파일의 행 조작

 

행 조작 프로그램 작성

파일을 열어 다음과 같이 조작하여 저장하는 프로그램을 작성하라

  • ./MyPythonFiles/mydata.txt 파일을 사용한다
  • 파일 조작 내용은 다음과 같다
    • 1~3번째 행을 삭제한다
    • 파일의 각 행을 길이 별로 정렬한다 (길이에 행 번호는 포함하지 않음)
    • 마지막 행에 “Good luck to you!\n”를 추가한다
    • 새롭게 1번부터 시작하는 행 번호를 붙여 mydataT.txt 로 저장한다
# mydata.txt
1 Time doesn't wait for anyone.
2 Idleness is an enemy to success.
3 More haste, less speed.
4 Make hay while the sun shines.
5 Every failure is a stepping stone to success.
6 A friend is a second self.
7 Life isn't always what one like.
8 It doesn't hurt to try.
9 He who laughs alst, laughs best.
10 Rather be dead then cool.
11 Learning to love yourself is the greatest love of all.
# mydataT.txt
1 It doesn't hurt to try.
2 Rather be dead then cool.
3 A friend is a second self.
4 Make hay while the sun shines.
5 Life isn't always what one like.
6 He who laughs alst, laughs best.
7 Every failure is a stepping stone to success.
8 Learning to love yourself is the greatest love of all.
9 Good luck to you!
import os

fileR = '/workspace/MOOC_L2_Python_for_w/01_File_IO/MyPythonFiles/mydata.txt'
fileW = '/workspace/MOOC_L2_Python_for_w/01_File_IO/MyPythonFiles/mydataT.txt'
# 1~3번째 행을 삭제한다
# 파일의 각 행을 길이 별로 정렬한다 (길이에 행 번호는 포함하지 않음)
# 마지막 행에 “Good luck to you!\n”를 추가한다
# 새롭게 1번부터 시작하는 행 번호를 붙여 mydataT.txt 로 저장한다
# 문자열, 문자열 list, built-in함수(enumerate, zip, map)
import pprint as pp

if os.path.exists(fileR) :
    # 여기에 코드를 작성하세요!
    with open(fileR, 'r') as fp :
        r = fp.readlines()       
        rn = r[3:]
        rn = [x.split(maxsplit=1, sep=' ')[1] for x in rn]
        rn.sort(key=len)#, reverse=True)
        rn.append('Good luck to you!\n')
        rn = [ f'{idx} {x}' for idx, x in enumerate(rn, start=1) ]
        #pp.pprint(rn)  #줄바꿈으로 프린트하기 위해 pprint 사용
        
    with open(fileW, 'w') as wp :
        wp.write(''.join(rn))
        
            
    print(f"{fileR!r} transformation success!!")
else :
    print(f"{fileR!r} doesn\'t exist")

 

 

열 조작 프로그램 작성

파일을 열어 다음과 같이 조작하여 저장하는 프로그램을 작성하라

  • /content/drive/MyDrive/MyPythonFiles/mydata2.txt 파일을 사용한다
  • 파일 조작 내용은 다음과 같다
    • 1번, 6번 열을 교환하고, 3번, 4번 열을 교환한다
    • 마지막 열을 삭제한다
    • 교환을 위한 함수와 삭제를 위한 함수를 각각 작성하여 사용한다
    • mydata2T.txt 로 저장한다
# mydata2.txt

1 283 748 328 57 454 7 148 289
2 240 996 7 578 826 254 65 272
3 754 674 781 925 681 656 963 445
4 700 304 598 584 469 40 808 954
5 94 27 374 587 373 912 218 447
6 216 487 800 320 434 324 449 756
7 889 742 259 636 71 194 598 391
8 308 623 9 993 426 567 243 629
9 131 668 137 654 321 758 301 742
10 51 331 211 408 817 529 513 161
# mydata2T.txt
1 7 748 57 328 454 283 148
2 254 996 578 7 826 240 65
3 656 674 925 781 681 754 963
4 40 304 584 598 469 700 808
5 912 27 587 374 373 94 218
6 324 487 320 800 434 216 449
7 194 742 636 259 71 889 598
8 567 623 993 9 426 308 243
9 758 668 654 137 321 131 301
10 529 331 408 211 817 51 513
import os

fileR = '/workspace/MOOC_L2_Python_for_w/01_File_IO/MyPythonFiles/mydata2.txt'
fileW = '/workspace/MOOC_L2_Python_for_w/01_File_IO/MyPythonFiles/mydata2T.txt'

# 1번, 6번 열을 교환하고, 3번, 4번 열을 교환한다
# 마지막 열을 삭제한다
# 교환을 위한 함수와 삭제를 위한 함수를 각각 작성하여 사용한다
# mydata2T.txt 로 저장한다
import pprint as pp

def exchangeCols(data, c1, c2):
    for x in data :
        x[c1], x[c2] = x[c2], x[c1]

def deleteColumn(data, c):
    for x in data :
        del x[c]

if os.path.exists(fileR) :
    # 여기에 코드를 작성하세요
    with open(fileR, 'r') as fp :
        r = fp.readlines()
        rn = [x.split() for x in r]
        exchangeCols(rn, 1, 6)
        exchangeCols(rn, 3, 4)
        deleteColumn(rn, -1)
    
    with open(fileW, 'w') as fp :
        rn = '\n'.join([' '.join(x) for x in rn])
        fp.write(rn)
    print(rn)

    print(f"{fileR!r} transformation success!!")
else :
    print(f"{fileR!r} doesn\'t exist")

 

 


파일, 디렉터리 복사

  • File객체의 read(), write()를 사용하여 1개 파일 복사
  • shutil 모듈의 copy() 함수를 사용하여 1개 파일 복사
    • shutil.copy(원본파일, 사본파일)
  • distutils.dir_util의 copy_tree() 함수를 사용하여 1개 디렉터리 복사
    • distutils.dir_util.copy_tree(원본디렉터리, 사본디렉터리)

 

import os

fileR = './MyPythonFiles/letter.txt'
fileW = './MyPythonFiles/letter_cp.txt'

if os.path.exists(fileR) :
    with open(fileR, 'r') as myfileR, open(fileW, 'w') as myfileW:
        mycontents = myfileR.read()
        myfileW.write(mycontents)

    print(f"{fileR!r} copy success!!")
else :
    print(f"{fileR!r} doesn\'t exist")
    
###############################################

import os,shutil

fileR = './MyPythonFiles/letter.txt'
fileW = './MyPythonFiles/letter_cp2.txt'

if os.path.exists(fileR) :
    # 파일 복사 코드 작성
    shutil.copy(fileR, fileW)    
    
    print(f"{fileR!r} copy success!!")
else :
    print(f"{fileR!r} doesn\'t exist")
    
###############################################

import os
from distutils.dir_util import copy_tree
dirR = './MyPythonFiles/TextFiles'
dirW = './TextFiles' 

if os.path.exists(dirR) :
    # 디렉터리 복사 코드 작성
    copy_tree(dirR, dirW)   
    
    print(f"{dirR!r} copy success!!")
else :
    print(f"{dirR!r} doesn\'t exist")

 

binary 파일 저장 - pickle 모듈

  • 객체 serialization/deserialization을 수행
  • Serialization : 객체의 상태를 메모리나 영구 저장 장치에 저장이 가능한 정보로 바꾸는 것
  • Deserialization : binary 파일을 읽어 객체로 복원하는 작업
  • open() 함수를 사용하여 pickle 파일에 쓰기 작업 할 때 'wb' 모드 사용
    • pickle.dump(객체, file_handle)
  • open() 함수를 사용하여 pickle 파일에서 읽기 작업할 때 'rb' 모드 사용
    • X = pickle.load(file_handle)
import pickle

# data.pkl에 객체 D, E 쓰기 - serialization

D = {'A' : 65, 'B' : 66}
E = [1, 2, 3, 4, 5]
with open('data.pkl', 'wb') as fp:
      # dict object
    pickle.dump(D, fp)
      # list object
    pickle.dump(E, fp)

print('write - data.pkl')

##############################

# data.pkl 에서 객체 2개 읽기 - deserialization

with open('data.pkl', 'rb') as fp :
      # dict object
    X = pickle.load(fp)
    Y = pickle.load(fp)
      # list object

print(X, Y)

#출력
{'A': 65, 'B': 66} [1, 2, 3, 4, 5]

##############################

# data.pkl 에서 객체 여러개 읽기(EOFError) - deserialization
with open('data.pkl', 'rb') as fp :
    while True :
        try :
            X = pickle.load(fp)
            print(X)
        except EOFError :
            break
            
#출력
{'A': 65, 'B': 66}
[1, 2, 3, 4, 5]

 

binary 파일 저장 - shelve 모듈

  • key 를 이용해 객체를 저장하고 불러옴
    • key 는 문자열을 사용함
  • mode 부여 필요 없음
    • 읽고, 쓰기 모두 가능하게 열림
  • 한 번 쓰기 한 내용은 계속 유지됨
  • 같은 ‘key’로 여러 번 저장 시 최근 것으로 저장됨 (갱신)
  • Windows에서는 X.bak. X.dat, X.dir 세 개의 파일이 생성되고, Linux에서는 X.db 파일이 생성됨

 

import shelve
fruits = ['orange', 'banana', 'apple']

with shelve.open('myshelf') as mydata :
    mydata['fruits'] = fruits  # 쓰기 작업
    X = mydata['fruits']       # 읽기 작업
    print(X)
    
>>
['orange', 'banana', 'apple']

import shelve
fruits = ['orange', 'apple']
myStr = 'hello!'
myValue = 100.2

with shelve.open('myshelf') as mydata:
     mydata['fruits'] = fruits   # 쓰기
     mydata['myStr']  = myStr
     mydata['myValue'] = myValue
     mydata['myValue'] = 200.54
     print(list(mydata.keys()))
     print(list(mydata.values()))
     print(mydata['myValue'])
     print(mydata['fruits'])     # 읽기
     print(mydata['myStr'])
     
 >>
['fruits', 'myStr', 'myValue']
[['orange', 'apple'], 'hello!', 200.54]
200.54
['orange', 'apple']
hello!
반응형

'Python' 카테고리의 다른 글

Series  (0) 2023.03.21
Pandas  (0) 2022.12.09
list/lambda/numpy/pandas/matplotlib  (0) 2022.02.02