How to use the expanduser and exists modules together
Here's the code first
user = os.path.expa开发者_Go百科nduser('~\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:
os.path.exists(os.path.join(user,'whatever.txt'))
Note that r'\whatever.txt'
is an absolute path, so
os.path.join(user,r'\whatever.txt')
would return r'\whatever.txt'
, ignoring the value of user
.
If you want to look for whatever.txt
inside the user
directory, 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'
.
精彩评论