Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 无法打开CSV文件_Swift_Csv - Fatal编程技术网

Swift 无法打开CSV文件

Swift 无法打开CSV文件,swift,csv,Swift,Csv,我试图在iPad的文档目录或临时目录中创建一个简单的CVS文件。该代码如下: let fileName = "test.csv" _ = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName) 然后,我尝试使用github中的CSV.swift库修改该文件,如下所示: let stream = OutputStream(toFileAtPath: "test.csv",

我试图在iPad的文档目录或临时目录中创建一个简单的CVS文件。该代码如下:

 let fileName = "test.csv"

        _ = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
然后,我尝试使用github中的CSV.swift库修改该文件,如下所示:

let stream = OutputStream(toFileAtPath: "test.csv", append: false)!

        let csv = try! CSVWriter(stream: stream) // Error at this line


        try! csv.write(row: headerarray)
        try! csv.write(row: dataarray)

        csv.stream.close()
出于某种原因,我在说CSV.CSVError.cannotOpenFile:file/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift时出错


看起来我没有正确创建.csv文件

您正在丢弃第二行中临时目录的路径。这是你的问题。因此,您不是在临时目录中添加
fileName
,而是尝试将其添加到硬盘的根目录中。我怀疑您对此有权限,因此无法创建该文件。尝试构建完整的路径名,就像我在下面函数的第一行中所做的那样

下面是一个函数,它使用streams将字符串写入临时目录中的文件

func streamTextToFile(_ text: String) {
  let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test.csv")
  guard let stream = OutputStream(toFileAtPath: url.path, append: false) else { return }
  let data = [UInt8](text.utf8)
  stream.open()
  stream.write(data, maxLength: data.count)
  stream.close()
}
下面是一些示例输出。