os.path.abspath('file1.txt')没有返回正确的路径 [英] os.path.abspath('file1.txt') doesn't return the correct path

查看:259
本文介绍了os.path.abspath('file1.txt')没有返回正确的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说文件'file1.txt'的路径是/home/bentley4/Desktop/sc/file1.txt 说我当前的工作目录是/home/bentley4

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')

返回/home/bentley4/file1.txt

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

返回False. 如果我这样做

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

它返回/home/bentley4/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?

推荐答案

os.path.abspath(filename)返回从当前工作目录看到的绝对路径.它不会检查文件是否实际存在.

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

如果要使用/home/bentley4/Desktop/sc/file1.txt的绝对路径,并且您在/home/bentley4中,则必须使用os.path.abspath("Desktop/sc/file1.txt").

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").

这篇关于os.path.abspath('file1.txt')没有返回正确的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆