[swift] Swift로 디렉토리 생성 후 파일 내용 수정하기

이번에는 Swift 언어를 사용하여 디렉토리를 생성하고, 해당 디렉토리 안에 파일을 만들고 내용을 수정하는 방법에 대해 알아보겠습니다.

디렉토리 생성하기

디렉토리를 생성하기 위해서는 FileManager 클래스를 사용합니다. 먼저 디렉토리를 생성할 경로와 이름을 지정하고, createDirectory 메서드를 사용합니다.

import Foundation

let fileManager = FileManager.default
let directoryURL = URL(fileURLWithPath: "path/to/your/directory")

do {
    try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print(error)
}

위 코드에서 fileURLWithPath 메서드에 경로를 지정하고, createDirectory 메서드를 사용하여 디렉토리를 생성합니다.

파일 생성 및 내용 수정하기

이어서 파일을 생성하고 내용을 수정해보겠습니다. 파일을 생성하는 방법은 다음과 같습니다.

let fileURL = directoryURL.appendingPathComponent("example.txt")

do {
    try "Hello, Swift!".write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
    print(error)
}

위 코드에서는 appendingPathComponent 메서드를 사용하여 파일의 경로를 지정하고, write 메서드를 사용하여 파일에 내용을 작성합니다.

마치며

이렇게 Swift를 사용하여 디렉토리를 생성하고 파일을 만들고 내용을 수정하는 방법에 대해 알아보았습니다. 파일 관리와 관련된 작업을 할 때 유용하게 활용할 수 있을 것입니다.

참고문헌: Apple Developer Documentation - FileManager

다음에 또 도움이 필요하시면 언제든 물어보세요!