python file
[Python] 텍스트 파일에 내용 추가
[Python] 텍스트 파일에 내용 추가
2023.01.18Python에서 텍스트 파일에 내용을 추가하려면, 먼저 파일을 열어야 합니다. 파일을 추가 모드로 열려면 open 시 mode에 'a'를 입력하여 append 파일 모드를 사용해야 합니다. 파일을 열고 파일에 내용을 추가 하기 위해서 file.write() 함수를 사용합니다. with open("example.txt", "a") as file: file.write("This text will be added to the file.") 다른 방법으로는 아래와 같이 작성 할 수 있습니다. f = open("example.txt", "a") f.write("This text will be added to the file.") f.close() 더보기 참고 : 'w' 파일 모드를 사용하면 파일을 쓰기 모드로 열..
[Python] File 끝 확인
[Python] File 끝 확인
2023.01.18Python 파일의 끝을 찾기 위한 방법을 소개하겠습니다. 파일을 읽어들이는 open() 함수를 사용합니다. 예를 들어, myfile.txt라는 파일을 읽어들이는 경우 아래와 같은 코드를 사용할 수 있습니다. with open("myfile.txt", "r") as f: lines = f.readlines() print(lines[-1]) 위 코드에서 readlines() 함수를 사용하여 파일의 모든 라인을 읽어들입니다. 그리고 lines 리스트의 마지막 요소를 출력하면 파일의 끝을 찾을 수 있습니다. 간편하게 파일을 열고 닫기 위해서 with open을 사용하였습니다. (파일을 읽어들이는 경우 seek() 함수를 사용하여 파일의 끝에서부터 일정 길이만큼 파일을 읽어들일 수도 있습니다.) read(), ..
[Python] File 수정, 생성 시간 확인하기
[Python] File 수정, 생성 시간 확인하기
2023.01.18Python으로 파일 수정 시간, 생성 시간을 확인하려면 os.path 모듈을 사용할 수 있습니다. import os file_path = "path/to/file.py" modification_time = os.path.getmtime(file_path) creation_time = os.path.getctime(file_path) print("Modification time:", modification_time) print("Creation time:", creation_time) 위 코드에서 os.path.getmtime(file_path)는 파일의 수정 시간을 반환하며, os.path.getctime(file_path)는 파일의 생성 시간을 반환합니다. Output: Modification tim..
[Python] File 개수 확인
[Python] File 개수 확인
2023.01.18Python으로 파일 개수를 확인하려면, 먼저 해당 폴더에 있는 파일들을 리스트로 받아와야 합니다. 그리고 그 리스트의 길이를 확인하면 파일 개수를 알 수 있습니다. import os folder_path = "path/to/folder" file_list = os.listdir(folder_path) file_count = len(file_list) print(file_count) Output : 13 파일 개수를 확인하는 다른 방법은 glob 라이브러리를 사용하면 특정 경로에 있는 파일들을 패턴으로 찾을 수 있습니다. folder_path + '/*'라는 패턴으로 해당 폴더 안에 있는 모든 파일을 찾아서 그 개수를 확인합니다. import glob folder_path = "path/to/folder..
[Python] 파일명, 디렉토리 경로 추출
[Python] 파일명, 디렉토리 경로 추출
2021.07.071. 파일 목록 얻기 glob.glob(wildcard) - 유닉스 경로명 패턴 스타일로 파일 목록을 얻을 수 있다. os.listdir(path) - 지정된 디렉토리의 전체 파일 목록을 얻을 수 있다. dircache.listdir(path) - os.listdir(path)와 동일한 파일 목록을 전달한다. path가 변경되지 않았을 때, dircache.listdir()은 다시 디렉토리 구조를 읽지 않고 이미 읽은 정보를 활용 dircache.annotate(head, list) - 일반 파일명과 디렉토리명을 구분해주는 함수 2. 디렉토리 os.chdir(path) - 작업하고 있는 디렉토리 변경 os.getcwd() - 현재 프로세스의 작업 디렉토리 얻기 os.remove( filename or p..