Docker环境下无法找到/创建新文件问题求助
Hey there! Let's break down what's going on here with your Docker and Python issue—this is a common pitfall for folks new to containerization, so let's fix it step by step.
1. Where is newImg.png?
Docker containers have their own isolated file systems. When your code runs inside the container, the newImg.png file is being created inside the container's working directory, not on your local machine's project folder.
To get the file onto your host machine, you need to use a bind mount when running the container. This syncs a directory on your host with a directory inside the container. For example:
docker run -v /path/to/your/local/project:/app chriscrutt/heyyo
Replace /path/to/your/local/project with the actual path to your project folder on your host, and /app with the working directory specified in your Dockerfile (if you didn't set a WORKDIR, it'll be the default root or /app depending on the base image).
If you just want to check if the file exists inside the container first, you can run:
# Get the container ID (even if it's stopped) docker ps -a # Enter the container's shell docker exec -it <your-container-id> /bin/bash # List files to see if newImg.png is there ls -l
2. Why can't you open the file (even if you find it)?
Your code has a critical mistake that's corrupting the PNG file: you're converting the decoded byte stream to a string before writing it.
Look at this snippet:
newImg = open("newImg.png", "w+") newImg.write(str(decoded_string))
decoded_string is a byte object (from base64.b64decode()). Converting it to a string adds extra characters like b' at the start and escape sequences, which breaks the PNG file structure.
Fix the file writing logic
You need to open the file in binary write mode (wb) and write the byte stream directly, no string conversion needed. Also, using with statements is better practice—it automatically closes files for you, avoiding resource leaks:
# Replace your current write logic with this with open("newImg.png", "wb") as newImg: newImg.write(decoded_string)
Also, note that Image.open('newImg.png').show() won't work inside a Docker container (most containers don't have a graphical environment to display the image). You can replace that with a quick validation check instead, like printing the image size to confirm it's valid.
Corrected Full Code Example
import base64 from PIL import Image # Read and encode the original image with open("testImg.jpg", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) # Decode and write the valid PNG file decoded_string = base64.b64decode(encoded_string) with open("newImg.png", "wb") as newImg: newImg.write(decoded_string) # Optional: Verify the file is valid try: img = Image.open("newImg.png") print(f"Success! Valid PNG with size: {img.size}") except Exception as e: print(f"Failed to open PNG: {str(e)}")
内容的提问来源于stack exchange,提问作者chriscrutt

