I have a code that writes all the bytes of all the.jpg files in a folder but it's not working, after running it just filling itself with the bytes and not the.jpg files.
code:
import os
def main():
path = __file__ #name of file = file.py
path = path.replace('file.py', '') # replace the name of file to get folder path
your_path = path #path of imgs and python file
files = os.listdir(your_path)
keyword = "*.jpg"
for file in files:
if os.path.isfile(os.path.join(your_path, file)):
f = open(os.path.join(your_path, file),'wb')
for x in f:
if keyword in x:
x = b'\0' #some bytes
f.write(x)
main()
output:
Traceback (most recent call last):
File "C:\Users\admin\Desktop\danger\file.py", line 20, in <module>
File "C:\Users\admin\Desktop\danger\file.py", line 14, in main
io.UnsupportedOperation: read
and after execution the file.py is 0 filled but not the.jpg files in the same folder.
You can't read a file that you have opened it with wb
mode. wb
mode indicates that you want to write something into it.
import PIL.Image as Image
import io
mport os
def main():
path = __file__ #name of file = file.py
path = path.replace('file.py', '') # replace the name of file to get folder path
your_path = path #path of imgs and python file
files = os.listdir(your_path)
keyword = "*.jpg"
for file in files:
if file.endswith(keyword):
jpg_path = os.path.join(your_path, file)
if os.path.isfile(jpg_path):
pil_im = Image.open(jpg_path)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
# This is a bytearray of your image. Do rest of your coding...
main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.