简体   繁体   English

Python function 将字节数组写入文件夹中的所有jpg文件

[英]Python function to write byte array to all jpg files in the folder it is

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.我有一个代码将所有 .jpg 文件的所有字节写入一个文件夹中,但它不工作,在运行它之后只是用字节而不是 .jpg 文件填充自己。

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: 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.执行后,file.py 填充为 0,但同一文件夹中的 .jpg 文件不填充。

You can't read a file that you have opened it with wb mode.您无法读取使用wb模式打开的文件。 wb mode indicates that you want to write something into it. wb模式表示你想往里面写东西。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM