Here’s the code first
user = os.path.expanduser('~\AppData\Local\Temp')
os.path.exists(user,'\whatever.txt')
Now the problem is, when I run it it says:
Traceback (most recent call last):
File “pyshell#7”, line 1, in module
os.path.exists(user,’\whatever.txt’)TypeError: exists() takes exactly 1
argument (2 given)
How do I fix the problem?
Use os.path.join to join two path fragments together:
Note that
r'\whatever.txt'is an absolute path, soos.path.join(user,r'\whatever.txt')would returnr'\whatever.txt', ignoring the value ofuser.If you want to look for
whatever.txtinside theuserdirectory, then you need to use a relative path by removing the backslash.PS: Python assigns special meaning to certain characters preceded by backslashes.
'\t'is a tab character for example. You generally don’t intend for backslashes to be interpreted in this way in a path, so — even though all the backslashes in your post are interpreted literally — it is generally a good idea to get in the habit of using raw strings (e.g.r'~\AppData\Local\Temp'to specify paths so you don’t get unexpected surprises later. Or, you could use forward slashes instead:'~/AppData/Local/Temp'.