개발자/파이썬 Python

파이썬 파일 찾고 읽고 쓰고 복사 이동 삭제 코드

지구빵집 2023. 1. 2. 09:57
반응형

 

 

파이썬의 장점 중 하나는 일률적인 업무를 돕는 프로그램을 쉽게 만들 수 있다는 점이다. 이런 것이 가능한 이유는 파일과 디렉터리를 쉽게 관리할 수 있기 때문이다. 파일, 디렉터리 관리와 관련된 패키지는 os, shutil이다. 각각 용도에 따라 다르게 사용된다. 

 

# file Detection

import os
path = "C:\\Users\\User\\Desktop\\test.txt"
if os.path.exists(path):
    print("That location exists!")
    if os.path.isfile(path):
        print("That is a file")
    elif os.path.isdir(path):
        print("That is a directory!")
else:
    print("That location doesn't exist!")

 

 

# file Read

try:
    with open('test.txt') as file:
        print(file.read())
except FileNotFoundError:
    print("That file was not found :(")

 

 

# file Write

text = "Yooooooooo\nThis is some text\nHave a good one!\n"

with open('test.txt','w') as file:
    file.write(text)

 

 

# file copy

# copyfile() =  copies contents of a file
# copy() =      copyfile() + permission mode + destination can be a directory
# copy2() =     copy() + copies metadata (file’s creation and modification times)

import shutil

shutil.copyfile('test.txt','copy.txt') #src,dst

 

# file move

import os

source = "C:\\Users\\User\\Desktop\\source.txt"
destination = "C:\\Users\\User\\Desktop\\destination.txt"

try:
    if os.path.exists(destination):
        print("There is already a file there")
    else:
        os.replace(source,destination)
        print(source+" was moved")
except FileNotFoundError:
    print(source+" was not found")

 

 

# file delete

import os
import shutil

path = "test.txt"

try:
    os.remove(path)    #delete a file
    #os.rmdir(path)     #delete an empty directory
    #shutil.rmtree(path)#delete a directory containing files
except FileNotFoundError:
    print("That file was not found")
except PermissionError:
    print("You do not have permission to delete that")
except OSError:
    print("You cannot delete that using that function")
else:
    print(path+" was deleted")

 

 

참고

 

[Python] 파이썬 하위 디렉토리(파일) 검색하는 방법

[Python] 파이썬 디렉토리 및 파일 전체를 복사 또는 일괄 삭제하는 방법 shutil.copytree(), shutil.rmtree()

[Python] 파이썬 파일 및 디렉토리(폴더) 삭제방법 : 파일, 디렉토리 무조건 삭제 하는 방법 : shutil , os

[Python] 파이썬 파일(디렉토리)처리 총정리: 경로 확인,경로 변경, 파일이름 변경 

 

 

파이썬 파일 찾고, 읽고, 쓰고, 복사, 이동, 삭제 코드

 

 

 

 

 

 

 

 

 

 

 

반응형