1

I am trying to read data from a jpg file using the open() function in python. For some reason, some of the file data is being lost. Here is what I tried:

file = open(imageDir, 'r')
data = file.read()
print data

When I try to re-write the data into a new file, the new file is corrupt.

1
  • How do you know that? Also, what is the meaning of "lines" in a jpg file? Commented Oct 26, 2019 at 18:01

2 Answers 2

3

Use 'rb' for binary file. Also, I suggest you not use dir for what is actually a filename; and use the context syntax for the read operation.

with file = open(filename, 'rb')
     data = file.read()
Sign up to request clarification or add additional context in comments.

2 Comments

dir is a built-in global function, one more reason why it's a bad variable name
Actually it's invalid syntax...
1

You should open file in binary mode like this

file = open(dir, 'rb')

By default it’s opened in text mode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.