yaslab / CSV.swift

CSV reading and writing library written in Swift.
MIT License
661 stars 78 forks source link

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

Open armaghan84 opened 4 years ago

armaghan84 commented 4 years ago

[

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

](url)

joris1995 commented 4 years ago

Same issue here. Any solution?

zant commented 4 years ago

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
}
johncpang commented 4 years ago

You have a URL object, just use it directly:

let stream = OutputStream(url: url, append: false)!
Pasta commented 4 years ago

same issue.

mash3l777 commented 4 years ago

same issue.

willm132 commented 3 years ago

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?

timefrancesco commented 2 years ago

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()
}