一个.我该如何获取目录中的所有txt文件?
我有一个目录路径,现在我应该找到所有的txt文件,并稍微更改每一个.
我试图运行所有文件:
let fileManager = NSFileManager.defaultManager() let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath) while let element = enumerator?.nextObject() as? String { } }
但我卡在那儿.如何检查文件类型是否为文本?
湾当我到达目录(在我运行的目录中)时,我想进入并在那里搜索,最后到达我所在的地方并继续.
a对我来说更重要但是如果我得到b的答案也会很好.
您可以在swift的语法中使用for ..来枚举NSEnumerator.
这是我编写的一个简单函数,用于提取文件夹中某些扩展名的所有文件.
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
原文地址:https://www.jb51.cc/swift/319302.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。