CSV.swift icon indicating copy to clipboard operation
CSV.swift copied to clipboard

Writing to file : Can't open file (CSV.CSVError.cannotOpenFile: file)

Open armaghan84 opened this issue 5 years ago • 8 comments

Screen Shot 2020-03-08 at 9 32 31 PM

armaghan84 avatar Mar 08 '20 16:03 armaghan84

Same issue here. Any solution?

joris1995 avatar Mar 13 '20 14:03 joris1995

I had the same problem at first and it was due to the file not existing yet. So I added a condition to create the file if that's the case:

if !FileManager.default.fileExists(atPath: path) {
  if !FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) {
    // throw error or something 
  }
}

Checking if the file is readable or writable could be also useful:

if !FileManager.default.isReadableFile(atPath: path) {
  // stuff
}

zant avatar Mar 22 '20 17:03 zant

You have a URL object, just use it directly:

let stream = OutputStream(url: url, append: false)!

johncpang avatar May 12 '20 19:05 johncpang

same issue.

Pasta avatar Jun 10 '20 06:06 Pasta

same issue.

mash3l777 avatar Jun 28 '20 09:06 mash3l777

I am having this issue also. Any resolution? I can verify that my file is being created and is readable/writable, but I keep getting the error let csv = try! CSVWriter(stream: stream) --> Fatal error: 'try!' expression unexpectedly raised an error: CSV.CSVError.cannotOpenFile:

When I try this:

if FileManager.default.isWritableFile(atPath: "\(fileURL)") {
     print("File is writable")
} else {
     print("File is read-only")
}

I am getting File is read-only Is there a way to change file permissions on create or am I doing something wrong?

willm132 avatar Jan 31 '21 22:01 willm132

What I've done to resolve it is to copy the file to the user cache directory.

Here is what I do from a file picked using a document picker :

public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        let myURL = url as URL 
        _ = myURL.startAccessingSecurityScopedResource()
        
        let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
        let temporaryFile = cachesDirectory.appendingPathComponent("tmp.csv")
        
        if FileManager.default.fileExists(atPath: temporaryFile.path) {
            try! FileManager.default.removeItem(atPath: temporaryFile.path)
        }
      
        try! FileManager.default.copyItem(at: url, to: temporaryFile)

      //then use temporaryFile as input to CSVReader

       //when finished remember to call 

      myURL.stopAccessingSecurityScopedResource()
}

timefrancesco avatar Mar 22 '22 22:03 timefrancesco