23

a. How should I get all the txt files in directory?

i got a path of directory and now i should find all the txt files and change every one a little.

i try to run over all the files:

let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)
while let element = enumerator?.nextObject() as? String {

    }
}

but I stuck there. How can I check if the filetype is text?

b. When i get to a directory (in the directory I run), I want get in and search there too, and in the end get out to the place I was and continue.

a is much more important to me but if I get an answer to b too it will be nice.

0

6 Answers 6

15

a. Easy and simple solution for Swift 3:

let enumerator = FileManager.default.enumerator(atPath: folderPath)
let filePaths = enumerator?.allObjects as! [String]
let txtFilePaths = filePaths.filter{$0.contains(".txt")}
for txtFilePath in txtFilePaths{
    //Here you get each text file path present in folder
    //Perform any operation you want by using its path
}

Your task a is completed by above code.

When talking about b, well you don't have to code for it because we are here using a enumerator which gives you the files which are inside of any directory from your given root directory.

So the enumerator does the work for you of getting inside a directory and getting you their paths.

Sign up to request clarification or add additional context in comments.

Comments

8

You can use for .. in syntax of swift to enumerate through NSEnumerator.

Here is a simple function I wrote to extract all file of some extension inside a folder.

func extractAllFile(atPath path: String, withExtension fileExtension:String) -> [String] {
    let pathURL = NSURL(fileURLWithPath: path, isDirectory: true)
    var allFiles: [String] = []
    let fileManager = NSFileManager.defaultManager()
    if let enumerator = fileManager.enumeratorAtPath(path) {
        for file in enumerator {
            if let path = NSURL(fileURLWithPath: file as! String, relativeToURL: pathURL).path
                where path.hasSuffix(".\(fileExtension)"){
                allFiles.append(path)
            }
        }
    }
    return allFiles
}



let folderPath = NSBundle.mainBundle().pathForResource("Files", ofType: nil)
let allTextFiles = extractAllFile(atPath: folder!, withExtension: "txt") // returns file path of all the text files inside the folder

1 Comment

i not with swift right now but it seems its gonna work thanks. there is an extension for windows folders? its even considered as file in the enumerator?
7

I needed to combine multiple answers in order to fetch the images from a directory and I'm posting my solution in Swift 3

func searchImages(pathURL: URL) -> [String] {
    var imageURLs = [String]()
    let fileManager = FileManager.default
    let keys = [URLResourceKey.isDirectoryKey, URLResourceKey.localizedNameKey]
    let options: FileManager.DirectoryEnumerationOptions = [.skipsPackageDescendants, .skipsSubdirectoryDescendants, .skipsHiddenFiles]

    let enumerator = fileManager.enumerator(
        at: pathURL,
        includingPropertiesForKeys: keys,
        options: options,
        errorHandler: {(url, error) -> Bool in
            return true
    })

    if enumerator != nil {
        while let file = enumerator!.nextObject() {
            let path = URL(fileURLWithPath: (file as! URL).absoluteString, relativeTo: pathURL).path
            if path.hasSuffix(".png"){
                imageURLs.append(path)
            }
        }
    }

    return imageURLs
}

and here is a sample call

let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
let destinationPath = documentsDirectory.appendingPathComponent("\(filename)/")

searchImages(pathURL: projectPath)

1 Comment

This works very well in the latest versions of Swift and I strongly recommend it.
7

Swift 4

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = URL(fileURLWithPath: documentsPath)

let fileManager = FileManager.default
let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: url.path)!
while let element = enumerator.nextObject() as? String, element.hasSuffix(".txt") {
    // do something

}

1 Comment

You have an error in your code, the element.hasSuffix() will stop the while loop on the first non .txt file it finds. So a solution would be to use the following loop: while let element = enumerator.nextObject() as? String { guard file.hasSuffix(".txt") else { continue } /*use the element here*/ }
4
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath!)!
while let element = enumerator.nextObject() as? String {
    if (element.hasSuffix(".txt")) { // element is a txt file }
}

1 Comment

Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others
3
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)
while let element = enumerator?.nextObject() as? String where element.pathExtension == "txt" {
    // element is txt file
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.