[英]Search for all txt files in directory - Swift
a. 一种。 How should I get all the txt files in directory?
我该如何获取目录中的所有txt文件?
i got a path of directory and now i should find all the txt files and change every one a little. 我有一个目录路径,现在我应该找到所有的txt文件,并改变每一个。
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. a
对我来说更重要但如果我得到b
的答案也会很好。
a. 一种。 Easy and simple solution for Swift 3:
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. 您的任务a由上面的代码完成。
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. 在谈论b时,你不必为它编写代码,因为我们在这里使用的枚举器为你提供了来自你给定根目录的任何目录内的文件。
So the enumerator does the work for you of getting inside a directory and getting you their paths. 因此,枚举器为您提供了进入目录并为您提供路径的工作。
You can use for .. in syntax of swift to enumerate through NSEnumerator. 您可以在swift语法中使用for ..来枚举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
I needed to combine multiple answers in order to fetch the images from a directory and I'm posting my solution in Swift 3 我需要结合多个答案才能从目录中获取图像,并在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)
Swift 4 斯威夫特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
}
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
}
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 }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.