반응형

🎯 이 글에서 배우는 것: 파일 읽기/쓰기, 폴더 탐색, 파일 관리 자동화
📂 파일 작업이 필요한 순간
- 설정 파일 저장/불러오기
- 로그 기록하기
- 텍스트 파일 일괄 처리
- 다운로드 폴더 자동 정리
AHK로 이 모든 걸 자동화할 수 있습니다!
📖 파일 읽기 (FileRead)
전체 파일 읽기
content := FileRead("C:\test.txt")
MsgBox(content)
인코딩 지정
; UTF-8 파일 읽기
content := FileRead("C:\test.txt", "UTF-8")
; UTF-16 파일 읽기
content := FileRead("C:\test.txt", "UTF-16")
파일 존재 확인 후 읽기
filePath := "C:\test.txt"
if FileExist(filePath) {
content := FileRead(filePath)
MsgBox(content)
} else {
MsgBox("파일이 없습니다!")
}
✏️ 파일 쓰기 (FileAppend)
새 파일 생성 또는 추가
; 파일 끝에 추가 (파일 없으면 생성)
FileAppend("Hello World`n", "C:\test.txt")
파일 덮어쓰기
기존 내용을 지우고 새로 쓰려면 먼저 삭제:
; 기존 파일 삭제 후 새로 작성
filePath := "C:\test.txt"
if FileExist(filePath)
FileDelete(filePath)
FileAppend("새로운 내용", filePath)
여러 줄 쓰기
content := "
(
첫 번째 줄
두 번째 줄
세 번째 줄
)"
FileAppend(content, "C:\multiline.txt")
인코딩 지정해서 쓰기
FileAppend("한글 내용", "C:\korean.txt", "UTF-8")
📋 줄 단위로 읽기 (Loop Read)
대용량 파일은 한 줄씩 처리하는 게 효율적입니다:
Loop Read "C:\data.txt" {
MsgBox("줄 " A_Index ": " A_LoopReadLine)
}
특정 줄만 처리
; 처음 5줄만 읽기
Loop Read "C:\data.txt" {
if (A_Index > 5)
break
MsgBox(A_LoopReadLine)
}
줄 필터링
; "ERROR"가 포함된 줄만 출력
Loop Read "C:\log.txt" {
if InStr(A_LoopReadLine, "ERROR")
MsgBox("에러 발견: " A_LoopReadLine)
}
📁 폴더 탐색 (Loop Files)
특정 폴더의 파일 목록
Loop Files "C:\Downloads\*.*" {
MsgBox("파일: " A_LoopFileName)
}
특정 확장자만
; txt 파일만
Loop Files "C:\Documents\*.txt" {
MsgBox(A_LoopFilePath)
}
; 이미지 파일들
Loop Files "C:\Pictures\*.jpg" {
MsgBox(A_LoopFileName)
}
하위 폴더 포함 (재귀)
Loop Files "C:\Projects\*.*", "R" { ; R = Recurse
MsgBox(A_LoopFilePath)
}
폴더만 탐색
Loop Files "C:\*", "D" { ; D = Directories only
MsgBox("폴더: " A_LoopFileName)
}
Loop Files 내장 변수
| 변수 | 설명 | 예시 |
|---|---|---|
A_LoopFileName |
파일명 | report.txt |
A_LoopFilePath |
전체 경로 | C:\Docs\report.txt |
A_LoopFileDir |
폴더 경로 | C:\Docs |
A_LoopFileExt |
확장자 | txt |
A_LoopFileSize |
크기(바이트) | 1024 |
A_LoopFileTimeModified |
수정일 | 20240115143022 |
🗑️ 파일 삭제 (FileDelete)
; 단일 파일 삭제
FileDelete("C:\temp\old.txt")
; 패턴으로 여러 파일 삭제
FileDelete("C:\temp\*.tmp") ; 모든 .tmp 파일 삭제
안전한 삭제
filePath := "C:\temp\old.txt"
if FileExist(filePath) {
FileDelete(filePath)
MsgBox("삭제 완료!")
} else {
MsgBox("파일이 없습니다")
}
📋 파일/폴더 복사 및 이동
파일 복사
FileCopy("C:\source.txt", "C:\backup\source.txt")
; 덮어쓰기 허용
FileCopy("C:\source.txt", "C:\backup\source.txt", true)
파일 이동/이름 변경
; 이동
FileMove("C:\Downloads\file.zip", "C:\Archive\file.zip")
; 이름 변경 (같은 폴더 내)
FileMove("C:\old_name.txt", "C:\new_name.txt")
폴더 복사/이동
; 폴더 복사
DirCopy("C:\Source", "C:\Backup")
; 폴더 이동
DirMove("C:\OldFolder", "C:\NewFolder")
📁 폴더 생성/삭제
; 폴더 생성
DirCreate("C:\NewFolder")
DirCreate("C:\Parent\Child\GrandChild") ; 중첩 폴더도 한번에
; 폴더 삭제 (빈 폴더만)
DirDelete("C:\EmptyFolder")
; 폴더와 내용물 전부 삭제
DirDelete("C:\FolderWithFiles", true) ; true = 재귀 삭제
🔧 실용적인 예제
예제 1: 로그 기록 함수
WriteLog(message) {
logFile := A_Desktop "\my_log.txt"
timestamp := FormatTime(, "yyyy-MM-dd HH:mm:ss")
FileAppend("[" timestamp "] " message "`n", logFile)
}
; 사용
WriteLog("스크립트 시작")
WriteLog("작업 완료")
WriteLog("에러 발생!")
예제 2: 다운로드 폴더 정리
#d::{ ; Win+D로 실행
downloads := "C:\Users\" A_UserName "\Downloads"
; 확장자별 폴더 생성
DirCreate(downloads "\Images")
DirCreate(downloads "\Documents")
DirCreate(downloads "\Archives")
; 파일 이동
Loop Files downloads "\*.jpg" {
FileMove(A_LoopFilePath, downloads "\Images\" A_LoopFileName)
}
Loop Files downloads "\*.png" {
FileMove(A_LoopFilePath, downloads "\Images\" A_LoopFileName)
}
Loop Files downloads "\*.pdf" {
FileMove(A_LoopFilePath, downloads "\Documents\" A_LoopFileName)
}
Loop Files downloads "\*.zip" {
FileMove(A_LoopFilePath, downloads "\Archives\" A_LoopFileName)
}
MsgBox("정리 완료!")
}
예제 3: 설정 파일 읽기/쓰기
; INI 스타일 설정 저장
SaveSettings(name, value) {
IniWrite(value, "C:\settings.ini", "Settings", name)
}
LoadSettings(name, default := "") {
return IniRead("C:\settings.ini", "Settings", name, default)
}
; 사용
SaveSettings("UserName", "홍길동")
SaveSettings("Theme", "Dark")
name := LoadSettings("UserName", "Guest")
theme := LoadSettings("Theme", "Light")
MsgBox("사용자: " name ", 테마: " theme)
예제 4: 파일 목록 생성
#l::{ ; Win+L로 실행
folder := "C:\Projects"
output := ""
Loop Files folder "\*.*", "R" {
output .= A_LoopFilePath "`n"
}
FileDelete(A_Desktop "\file_list.txt")
FileAppend(output, A_Desktop "\file_list.txt")
MsgBox("파일 목록이 바탕화면에 저장되었습니다!")
Run(A_Desktop "\file_list.txt")
}
예제 5: 오래된 파일 삭제
; 30일 이상 된 파일 삭제
CleanOldFiles(folder, days := 30) {
cutoff := DateAdd(A_Now, -days, "Days")
count := 0
Loop Files folder "\*.*" {
if (A_LoopFileTimeModified < cutoff) {
FileDelete(A_LoopFilePath)
count++
}
}
MsgBox(count "개 파일 삭제됨")
}
; 사용
CleanOldFiles("C:\Temp", 7) ; 7일 이상 된 파일 삭제
📂 경로 처리
SplitPath - 경로 분해
fullPath := "C:\Users\홍길동\Documents\report.docx"
SplitPath(fullPath, &fileName, &dir, &ext, &nameNoExt, &drive)
MsgBox("파일명: " fileName) ; report.docx
MsgBox("폴더: " dir) ; C:\Users\홍길동\Documents
MsgBox("확장자: " ext) ; docx
MsgBox("확장자 제외: " nameNoExt) ; report
MsgBox("드라이브: " drive) ; C:
경로 조합
folder := "C:\Projects"
fileName := "script.ahk"
fullPath := folder "\" fileName
MsgBox(fullPath) ; C:\Projects\script.ahk
🎮 실습 과제
- 바탕화면의 모든 .txt 파일 목록을 MsgBox로 표시
- "Hello AHK!"를 파일에 쓰고 다시 읽어서 표시
- 특정 폴더의 파일 개수와 총 용량 계산
정답 보기 👀
#Requires AutoHotkey v2.0
; 1. txt 파일 목록
F1::{
list := ""
Loop Files A_Desktop "\*.txt" {
list .= A_LoopFileName "`n"
}
MsgBox(list ? list : "txt 파일 없음")
}
; 2. 파일 쓰고 읽기
F2::{
testFile := A_Desktop "\test_ahk.txt"
FileDelete(testFile)
FileAppend("Hello AHK!", testFile)
content := FileRead(testFile)
MsgBox("읽은 내용: " content)
}
; 3. 파일 통계
F3::{
folder := A_Desktop
fileCount := 0
totalSize := 0
Loop Files folder "\*.*" {
fileCount++
totalSize += A_LoopFileSize
}
MsgBox("파일 수: " fileCount "`n총 용량: " Round(totalSize / 1024, 2) " KB")
}
📚 다음 시간 예고
다음 글에서는 문자열 처리를 배웁니다:
- SubStr, StrReplace
- 정규표현식 기초
- 텍스트 파싱
텍스트 마법사가 되어봅시다! ✨
🔑 오늘 배운 핵심 정리
| 함수 | 용도 | 예제 |
|---|---|---|
FileRead() |
파일 읽기 | FileRead("file.txt") |
FileAppend() |
파일 쓰기 | FileAppend("text", "file.txt") |
FileDelete() |
파일 삭제 | FileDelete("file.txt") |
FileCopy() |
파일 복사 | FileCopy("a.txt", "b.txt") |
FileMove() |
파일 이동 | FileMove("a.txt", "b.txt") |
FileExist() |
존재 확인 | if FileExist("file.txt") |
Loop Files |
파일 순회 | Loop Files "*.txt" |
Loop Read |
줄 단위 읽기 | Loop Read "file.txt" |
이전 글: [#11 GUI 기초]
다음 글: [#13 문자열 처리]
반응형
'🔬 과학·테크 > 🔥 AutoHotkey v2 입문 가이드' 카테고리의 다른 글
| AutoHotkey v2 입문 가이드 #14: 실전 예제 모음 - 바로 쓰는 스크립트 10선 (0) | 2025.12.17 |
|---|---|
| AutoHotkey v2 입문 가이드 #13: 문자열 처리 - 텍스트 다루기의 기술 (0) | 2025.12.16 |
| AutoHotkey v2 입문 가이드 #11: GUI 기초 - 나만의 창 만들기 (0) | 2025.12.14 |
| AutoHotkey v2 입문 가이드 #10: 키 리매핑 - 키보드 재창조하기 (0) | 2025.12.13 |
| AutoHotkey v2 입문 가이드 #9: 함수 기초 - 코드 재사용의 마법 (0) | 2025.12.12 |