파일 경로 알려주기
파이썬에서 파일을 불러오려면 파일의 경로를 확실히 알려줘야 한다.
그럴 때 쓸 수 있는 게 os와 pathlib이라는 파이썬 내장 모듈이다.
os
os 모듈로 운영체제 관련 기능을 쓸 수 있다
그 중에서 파일 경로랑 관련 있는 명령어는
os.getcwd()
get current directory
현재 위치를 가져온다
import os
# Get the current working directory
cwd = os.getcwd()
print(f"The current working directory is {cwd}")
# List all files and directories in the current working directory
entries = os.listdir(cwd)
print("Entries in the current directory:")
for entry in entries:
print(entry)
# Create a new directory
new_dir_path = os.path.join(cwd, 'new_directory')
try:
os.mkdir(new_dir_path)
print(f"Directory created at {new_dir_path}")
except FileExistsError:
print(f"Directory already exists: {new_dir_path}")
# Define the path to a new file within the new directory
new_file_path = os.path.join(new_dir_path, 'example.txt')
# Write text to the new file
with open(new_file_path, 'w') as file:
file.write('Hello, World!')
# Read the contents of the file
with open(new_file_path, 'r') as file:
content = file.read()
print(f"Content of {new_file_path}:")
print(content)
# Check if the file exists
file_exists = os.path.exists(new_file_path)
print(f"Does the file exist? {file_exists}")
# Rename the file
new_file_path_renamed = os.path.join(new_dir_path, 'renamed_example.txt')
os.rename(new_file_path, new_file_path_renamed)
print(f"File renamed to {new_file_path_renamed}")
# Remove the file
os.remove(new_file_path_renamed)
print(f"File {new_file_path_renamed} has been removed")
# Remove the directory (note: directory must be empty)
os.rmdir(new_dir_path)
print(f"Directory {new_dir_path} has been removed")
pathlib
pathlib
모듈은 경로를 쉽게 만들어준다. python 3.4부터 내장됐다.
from pathlib import Path
# Define the path to a directory
p = Path('/usr/local/bin')
# Iterate over the contents of the directory
for entry in p.iterdir():
if entry.is_file():
print(f'File: {entry.name}')
if entry.is_dir():
print(f'Directory: {entry.name}')
# Create a new directory
new_dir = p / 'my_new_directory'
new_dir.mkdir(exist_ok=True) # The `exist_ok` flag allows the directory to exist already
# Define the path to a new file within the new directory
new_file = new_dir / 'example.txt'
# Write text to the new file
new_file.write_text('Hello, World!')
# Read the contents of the file
print(new_file.read_text())
# Check if the file exists
print(f'Does the file exist? {new_file.exists()}')
# Rename the file
new_file.rename(new_dir / 'renamed_example.txt')
# Remove the file (be careful with this operation!)
(new_dir / 'renamed_example.txt').unlink()
# Remove the directory (only if it's empty)
new_dir.rmdir()
응용
두 모듈을 합쳐서 활용하면 상대적 경로로 파일을 가리킬 수 있다. 상대적 경로란 현재 파일의 경로로부터 출발해 위치를 지정하는 걸 말한다.
path = Path(os.getcwd()).parent / my_folder / my_file.file
path.is_file()
참고
'아카이브' 카테고리의 다른 글
chatcpt4로 custom gpt 만들기 (0) | 2023.11.14 |
---|---|
리스트 순서 섞기 random.shuffle (0) | 2023.11.14 |
판다스 데이터 저장 방법 및 파일 종류와 그 차이 (0) | 2023.11.11 |
데이터를 날려먹었다 (0) | 2023.11.10 |
블로그를 다시 쓰기로 했다 (0) | 2023.11.09 |