簡體   English   中英

Python function 將字節數組寫入文件夾中的所有jpg文件

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

我有一個代碼將所有 .jpg 文件的所有字節寫入一個文件夾中,但它不工作,在運行它之后只是用字節而不是 .jpg 文件填充自己。

代碼:

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

執行后,file.py 填充為 0,但同一文件夾中的 .jpg 文件不填充。

您無法讀取使用wb模式打開的文件。 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