import os path = chap_name if not os.path.exists(path): os.makedirs(path) filename = img_alt + '.jpg' with open(os.path.join(path, filename), 'wb') as temp_file: temp_file.write(buff)
Key point is to use os.makedirs
in place of os.mkdir
. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html
Open the file in binary mode as you are storing binary (jpeg) data.
In response to Edit 2, if img_alt sometimes has ‘/’ in it:
img_alt = os.path.basename(img_alt)
Related Posts:
- How do I copy a file in Python?
- How do I copy a file in Python?
- How to open a file using the open with statement
- Using “with open() as file” method, how to write more than once? [duplicate]
- How to read a file line-by-line into a list?
- TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python3
- How do I list all files of a directory?
- Find the current directory and file’s directory [duplicate]
- Confused by python file mode “w+”
- How to find if directory exists in Python
- File open and close in python
- Do I understand os.walk right?
- FileNotFoundError: [Errno 2] No such file or directory [duplicate]
- How to move a file in Python?
- Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory
- FileNotFoundError: [Errno 2] No such file or directory
- How to move a file in Python?
- How do you append to a file?
- Importing modules from parent folder
- Importing modules from parent folder
- Writing a list to a file with Python
- Why do I get “Pickle – EOFError: Ran out of input” reading an empty file?
- How do I copy a file in Python?
- How do I list all files of a directory?
- How do I check whether a file exists without exceptions?
- Call a function from another file?
- Writing a list to a file with Python
- How can I check file size in Python?
- Python list directory, subdirectory, and files
- Where does this come from: -*- coding: utf-8 -*-
- Open file in a relative location in Python
- Why am I getting a FileNotFoundError?
- Python: Write array values into file
- Importing variables from another file?
- How to copy files?
- Flask raises TemplateNotFound error even though template file exists
- importing external “.txt” file in python
- Search and replace a line in a file in Python
- How to save a dictionary to a file?
- How to open a file for both reading and writing?
- How do you read a file into a list in Python?
- SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
- What is the perfect counterpart in Python for “while not EOF”
- How do I get the full path of the current file’s directory?
- .write not working in Python
- How to convert a file into a dictionary?
- How to delete a specific line in a file?
- Python read in string from file and split it into values
- Extract a part of the filepath (a directory) in Python
- How often does python flush to a file?
- How to open every file in a folder
- TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
- Loading and parsing a JSON file with multiple JSON objects
- How can I find script’s directory?
- How to find out whether a file is at its `eof`?
- Python copy files to a new directory and rename if file name already exists
- Python IOError: File not open for reading
- ValueError: operands could not be broadcast together with shapes (5,) (30,)
- appending list but error ‘NoneType’ object has no attribute ‘append’
- Using Python 3 in virtualenv
- “Series objects are mutable and cannot be hashed” error
- Putting a simple if-then-else statement on one line [duplicate]
- matplotlib savefig() plots different from show()
- Converting list to numpy array
- How do I parse a string to a float or int?
- Use a.any() or a.all()
- What is the difference between Spyder and Jupyter?
- What is the maximum recursion depth in Python, and how to increase it?
- subprocess.check_output return code
- Why Python 3.6.1 throws AttributeError: module ‘enum’ has no attribute ‘IntFlag’?
- Creating 2D dictionary in Python
- Python: slicing a multi-dimensional array
- Python: pandas merge multiple dataframes
- Shuffle an array with python, randomize array item order with python
- How to count the NaN values in a column in pandas DataFrame
- How to install multiple python packages at once using pip
- Running Selenium with Headless Chrome Webdriver
- Make list of arrays in python
- In Python, what is `sys.maxsize`?
- Pyspark: Exception: Java gateway process exited before sending the driver its port number
- Converting from a string to boolean in Python?
- Import Error: No module named numpy Anaconda
- How to remove \n from a list element?
- Is it possible to decompile a compiled .pyc file into a .py file?
- Writing string to a file on a new line every time
- How can I get the list of files in a directory using C or C++?
- Creating lowpass filter in SciPy – understanding methods and units
- Python 2: AttributeError: ‘list’ object has no attribute ‘strip’
- Get Confusion Matrix From a Keras Multiclass Model
- AttributeError: ‘list’ object has no attribute ‘lower’ gensim
- Scikit-learn GridSearch giving “ValueError: multiclass format is not supported” error
- Convert R code into Python code using rpy2
- PIL: DLL load failed: specified procedure could not be found
- “Cannot access setup.py: No such file or directory” – can’t run any .py files?
- How does ajax work with python?
- RSA encryption and decryption in Python
- IPython, “name ‘plt’ not defined”
- ‘pyuic5’ is not recognized as an internal or external command
- ValueError: multiclass format is not supported
- Filtering a NumPy Array