In Python, I'm trying to open a file that gets saved to the %TEMP% directory. I've tried:
file = open("%TEMP%\file.txt")
and
file = open("%%TEMP%%\file.txt")
and
file = open("%TEMP%\\file.txt")
and
file = open("%%TEMP%%\\file.txt")
And always get (this one specifically for that last example):
IOError: [Errno 2] No such file or directory: '%%TEMP%%\\file.txt'
For sanity's sake, from Windows command prompt I do a type %TEMP%\\file.txt
and it prints out the file OK. Any help?
Use os.environ
import os
f = open(os.path.join(os.environ['TEMP'], 'file.txt'))
You can also use os.path.expandvars
import os
f = open(os.path.expandvars(r'%TEMP%\file.txt'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.