Do not use temporary folders per session
时间: 2024-02-19 10:58:16 浏览: 113
SpringBoot导入上传文件异常The temporary upload location is not valid
Sure, I understand. One way to avoid using temporary folders per session is to create a single temporary folder at the beginning of your program and reuse it throughout the program's execution. You can use the `tempfile` module in Python to create and manage temporary files and directories.
Here's an example code snippet that creates a temporary folder and uses it to store a file:
```python
import tempfile
# Create a temporary directory
temp_dir = tempfile.TemporaryDirectory()
# Create a file and write some data to it
with open(temp_dir.name + '/example.txt', 'w') as f:
f.write('Hello, world!')
# Read the data from the file
with open(temp_dir.name + '/example.txt', 'r') as f:
data = f.read()
print(data)
# Delete the temporary directory and its contents
temp_dir.cleanup()
```
In this example, the `TemporaryDirectory` function creates a temporary folder that will be automatically deleted when the program exits. The `name` attribute of the `TemporaryDirectory` object can be used to access the path to the temporary folder. You can then use this path to create and manipulate files within the temporary folder. Finally, you can call the `cleanup` method on the `TemporaryDirectory` object to delete the temporary folder and its contents.
阅读全文