
`is_writeable` 메서드는 파일이 쓰기 가능한지 여부를 확인하는 메서드입니다.
#hostingforum.kr
python
import os
file_path = 'test.txt'
if os.path.exists(file_path):
if os.access(file_path, os.W_OK):
print(f"{file_path}은 쓰기 가능합니다.")
else:
print(f"{file_path}은 쓰기 불가합니다.")
else:
print(f"{file_path}은 존재하지 않습니다.")
`os.access()` 함수는 파일이 쓰기 가능한지 여부를 확인하는 함수입니다. `os.W_OK`은 쓰기 가능을 의미합니다.
파일 모드에 대해 알기 위해서는 `open()` 함수의 `mode` 매개변수를 사용합니다.
#hostingforum.kr
python
# 쓰기 모드
with open('test.txt', 'w') as f:
pass
# 읽기 모드
with open('test.txt', 'r') as f:
pass
# 읽기와 쓰기 모드
with open('test.txt', 'a') as f:
pass
# 읽기와 쓰기 모드(파일이 이미 존재하면 내용을 덮어쓰지 않음)
with open('test.txt', 'a+') as f:
pass
# 쓰기 모드(파일이 이미 존재하면 내용을 덮어씀)
with open('test.txt', 'w') as f:
pass
# 쓰기 모드(파일이 이미 존재하면 내용을 덮어씀, 오류가 발생하지 않음)
with open('test.txt', 'x') as f:
pass
# 읽기 모드(파일이 이미 존재하면 오류가 발생함)
try:
with open('test.txt', 'r') as f:
pass
except FileNotFoundError:
print("파일이 존재하지 않습니다.")
`is_writeable` 메서드의 반환 값은 `True` 또는 `False`입니다.
#hostingforum.kr
python
import os
file_path = 'test.txt'
if os.path.exists(file_path):
if os.access(file_path, os.W_OK):
print(os.access(file_path, os.W_OK)) # True
else:
print(os.access(file_path, os.W_OK)) # False
else:
print(os.access(file_path, os.W_OK)) # False
2025-04-09 20:08