Search code examples
pythonencodingcopyjpeg

Python - Error while copying jpg files


I was done with copying txt files and tried to do the same with jpg files. But I am constantly getting an encoding error. My code is:

def fcopy(source, target):
data = ''
with open(source, encoding='Latin-1') as f:
    data = f.read()
    with open(target, 'w') as t:
            t.write(data)
fcopy("source.jpeg","dest.jpeg")

I tried using encoding = utf8 and utf16 also. But didn't work and error is as:

Traceback (most recent call last):
  File "C:/Users/Mark-II/Desktop/fileCopy.py", line 7, in <module>
    fcopy("source.jpeg","dest.jpeg")
  File "C:/Users/Mark-II/Desktop/fileCopy.py", line 3, in fcopy
    with open(source, encoding='Latin-1') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'source.jpeg'
>>> 

Please help.


Solution

  • Try opening the file in 'binary mode'. This defaults to text mode per the documentation on the open method. That explains why it works on text files and fails on non-text files like jpg images. When opening files in binary mode you do not need to use the named parameter for the encoding.

    def fcopy(source, target):
        with open(source, 'rb') as f:
            data = f.read()
        with open(target, 'wb') as t:
            t.write(data)
    
    fcopy("source.jpeg","dest.jpeg")