rgzip

Problem in creating gz file because connection cannot be opened


Has anyone seen this R error before or know how to fix it?

> test_file <- gzfile("test_file.txt.gz", "wb")
Error in gzfile("test_file.txt.gz",  : 
  cannot open the connection

Solution

  • check out this solution: Error in gzfile(file, "wb"): cannot open the connection or compressed file:

    I got this error when I was trying to write a file from RStudio and my destination file path was very long. I realized this could be a problem because when I wrote the file to another location with a shorter name and tried to copy it into my original destination, Windows gave me an error saying "File path too long". You might need to save the original file into another location with a shorter absolute path.

    Maybe try this:

    # Check current working directory and see if the path is very long!
    getwd()
    # set the current script's location as working directory
    setwd(dirname(rstudioapi::getSourceEditorContext()$path))
    
    # Or set working directory to a shorter path if needed
    # setwd("/path/to/your/directory")
    getwd()
    # Try opening the file with full path or in the correct directory
    test_file <- gzfile("test_file.txt.gz", "wb")
    
    # Write some content
    writeLines("Your text here", test_file)
    
    # Close the file connection
    close(test_file)