자신에게 친절할 것 :)

Data Science/Jupyter Notebook

[Jupyter Notebook] 폴더 생성 및 파일 이동

Tashapark 2024. 5. 22. 15:53
728x90

강의를 따라서 듣다가 

폴더를 구분해 놓지 않고 쓰고 있었다는 것을 확인하고 만들어서 data.csv는 저장했는데도 계속 에러가 떴다. 

 

이건 

현재 running 중인 파일이 데이터가 있는 폴더와 같은 폴더에 있지 않아서 생긴 문제였다.

그래서 옮기려고 했는데 잘 안 되서 검색해서 방법을 확인했다. 

 

어떻게 해도 ui 상에서는 이동이 안 되어서 주피터 노트북 상에서 그냥 폴더를 생성하고 기존 것은 삭제 했다.

(그냥 내가 방법을 못 찾은 것일지도 모르겠다. ;;)

 

구글 ,,, 검색은 중구난방이라 그냥 gpt에게 물어봤다. 

5단계로 나눠서 셀에 입력하라고 추천했고, 경로 때문에 조금 헤매다가 경우 방법을 찾았다. 

 

1. 현재 작업 디렉토리 확인

import os
print("Current working directory:", os.getcwd())

 

2. 파일 및 디렉토리 존재 여부 확인 및 생성

import os

source_path = '위에서 나온 현재 위치/파일명.csv'
destination_dir = '만들고 싶은 폴더명'
destination_path = os.path.join(destination_dir, '파일명.csv')

if not os.path.exists(destination_dir):
    os.makedirs(destination_dir)
    print(f"Directory {destination_dir} created.")
else:
    print(f"Directory {destination_dir} already exists.")

 

3. 파일 이동

import shutil

try:
    shutil.move(source_path, destination_path)
    print(f"File moved to {destination_path}")
except FileNotFoundError as e:
    print(f"Error: {e}")

 

4. 작업 디렉토리 변경

os.chdir(destination_dir)
print("New working directory:", os.getcwd())

 

5. 파일 확인 후 로드 (필요하다면)

import pandas as pd

new_file_path = '파일명.csv'
if os.path.exists(new_file_path):
    파일명_df = pd.read_csv(new_file_path)
    print("File loaded successfully!")
else:
    print("File not found in the new directory.")

 

++ 그때 저장이 안 된건지 이 글을 쓰면서 다시 확인해보니깐... 

.ipynb 파일이 다시 가장 상위 폴더로 옮겨졌던데.. 

왜인지는 모르겠다...

728x90
반응형