반응형
Python에서 파일 및 디렉토리 작업을 수행하기 위해 os 모듈과 shutil 모듈을 주로 사용합니다.
아래에 간단한 예시를 제공하겠습니다.
파일 작업
1. 파일 생성
>>> with open("example.txt", "w") as file:
... file.write("Hello, world!")
...
13
root@node3:Learn_Python$ ls -l
total 4
-rw-r--r-- 1 root root 13 Feb 29 10:56 example.txt
2. 파일 읽기
>>> with open("example.txt", "r") as file:
... contents = file.read()
... print(contents)
...
Hello, world!
3. 파일 쓰기
>>> with open("example.txt", "w") as file:
... file.write("New content")
...
11
$ cat example.txt
New content
4. 파일 삭제
>>> import os
>>> os.remove("example.txt")
$ ls -l example.txt
ls: cannot access 'example.txt': No such file or directory
디렉토리 작업
1. 디렉토리 생성
>>> import os
>>> os.mkdir("/root/Learn_Python/example_dir")
$ ls -l example_dir
total 0
2. 현재 디렉토리 변경
>>> import os
>>> os.chdir("/root/Learn_Python/example_dir")
3. 디렉토리 내 파일 및 디렉토리 목록 보기
>>> import os
>>> contents = os.listdir(".")
>>> print(contents)
[]
4. 디렉토리 삭제
>>> import shutil
>>> shutil.rmtree("/root/Learn_Python/example_dir")
$ ls -l example_dir
ls: cannot access 'example_dir': No such file or directory
위의 예시는 기본적인 파일 및 디렉토리 작업을 보여줍니다. os 모듈과 shutil 모듈은 더 많은 기능을 제공하므로 필요에 따라 해당 문서를 참조하여 활용할 수 있습니다.
728x90
반응형
'스크립트' 카테고리의 다른 글
액세스 로그 백업 스크립트 (0) | 2013.12.24 |
---|---|
[스크립트] 리눅스에서 ping 테스트 시 시작 표시하기(ping 정상 Bell 울림) (0) | 2013.09.10 |
아파치 서버의 로그 저장 스크립트 (0) | 2013.08.14 |
아파치 서버의 로그 삭제 스크립트 (0) | 2013.08.14 |
bind recursive clients 모니터링 (0) | 2013.08.14 |