Skip to content

Python:File

Automatically creating directories

상위 디렉터리가 존재하지 않을 경우 디렉터리를 생성하는 방법은 아래와 같다.

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    os.makedirs(os.path.dirname(filename))

Example

os.path.isfile(fname)
파일의 존재여부를 확인한다.
os.remove(filename)
파일을 제거한다.

Troubleshooting

File write EOL

write()사용시 OS환경에 따라 EOL이 CRLF또는 LR로 변경되는 현상이 발견될 수 있는다. 이 경우 write의 mode인자에 wb를 추가하면 입력한 EOL 그대로 적용된다.

Favorite site