춘식이를 좋아하는 개발자

[python] 디렉토리와 파일 본문

Study/Python

[python] 디렉토리와 파일

NaChoon 2022. 10. 7. 16:31

파이썬에는 다양한 모듈이 존재한다!

그 중 자주 사용하는 모듈로 linux 혹은 window cmd창 등의 command를 python에서도 사용하기 위해 os module을 많이 사용한다.

 

os 모듈은 따로 알아보도록 하고, 간단한 디렉토리와 파일 생성에 대해서 작성해보겠다.

 

다음과 같은 실습을 진행해보자!

import os


## basic
## CRUD directory and files

## get current directory path(pwd)
a = os.getcwd()
print(a)



os.chdir('../../')

## create file and write
file = open("./test.txt",'w')
file.write("Hello world!")
file.close()

## append text in file
file = open("./test.txt",'a')
file.write("\nMy name is JS")
file.close()

## read by line
file = open("./test.txt",'r')
for line in file :
    print(line)


## return to current directory
os.chdir(a)

위와 같이 코드를 실행하면 현재 위치한 디렉토리는 기준으로 이전,이전(../../) 디렉토리에 test.txt가 생성되는 것을 알 수있다.

python 내에서도 파일 수정 및 삭제, 읽어오기, 생성 등 다양하게 활용할 수 있다.

'Study > Python' 카테고리의 다른 글

[Python] os package  (0) 2022.09.06