Python 3 – os.tempnam() Method
In Python, the os
module provides access to the file system. The os.tempnam()
method is one of the useful methods in the os
module. The method returns a unique temporary filename that can be used to create a temporary file.
Syntax
The syntax of the os.tempnam()
method is:
os.tempnam([dir[, prefix]])
The dir
and prefix
are optional arguments. If not specified, the method uses the tempfile.gettempdir()
method to get the temporary directory and the prefix is set to 'tmp'
.
Return Value
The os.tempnam()
method returns a string representing the unique temporary filename.
Example
Here is an example that demonstrates the use of the os.tempnam()
method:
import os
# get the temporary file name
temp_file = os.tempnam()
print("Temp File: ", temp_file)
Output:
Temp File: /var/folders/61/2j57cdms1t1cjxhfbw8tztz00000gn/T/tmp000000
In this example, we imported the os
module and called the os.tempnam()
method to get the temporary filename. We then printed the temporary filename to the console.
Customizing the Temporary File
We can also pass in values for the dir
and prefix
parameters to customize the temporary filename.
Here is an example that demonstrates customizing the temporary filename:
import os
# get the temporary file name
temp_file = os.tempnam('/my/tmp/', 'temp_file_')
print("Temp File: ", temp_file)
Output:
Temp File: /my/tmp/temp_file_0000
In this example, we passed in /my/tmp/
as the directory and temp_file_
as the prefix. The os.tempnam()
method then created a temporary filename using the provided values.
Conclusion
In conclusion, the os.tempnam()
method is a useful method in Python for generating unique temporary filenames. It takes optional arguments for customizing the temporary file name. By using the os
module and the os.tempnam()
method, we can easily create temporary files in our Python programs.