Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

python - os.path.abspath('file1.txt') doesn't return the correct path

Say the path of the file 'file1.txt' is /home/bentley4/Desktop/sc/file1.txt Say my current working directory is /home/bentley4

import os
os.path.abspath('file1.txt')

returns /home/bentley4/file1.txt

os.path.exists('file1.txt')

returns False. If I do

os.path.abspath('file_that_does_not_exist.txt')

It returns /home/bentley4/file_that_does_not_exist.txt But again, this is not correct. The file does not even exist on my computer. Is there a way to get the correct absolute path from any directory I am currently working in? (aside from defining a new function)

So this only works when I am in the same directory as the existing file or in the directory one directory or more further from the path of the directory of that file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

os.path.abspath(filename) returns an absolute path as seen from your current working directory. It does no checking whether the file actually exists.

If you want the absolute path of /home/bentley4/Desktop/sc/file1.txt and you are in /home/bentley4 you will have to use os.path.abspath("Desktop/sc/file1.txt").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...