简体   繁体   中英

Print out *accurate* absolute path to files in Python 2 with oswalk + fnmatch

I've been tasked with finding out a way to search my entire hard drive for any given file using Python 2 in both Windows and Linux. I was excited to have pieced together various posts to concoct a solution, only to realize the paths being output by Python are not quite correct. Here are my results on Linux: 在此处输入图片说明

Unless the /home/pi directory is being queried 3 times from the for loops, I shouldn't be seeing the exact /home/pi/chromium-browser listed 3 times. I assume a couple of them are directories and one of them is the symlink/executable. However, the filepaths are [incorrectly] all the same.

Here is the same code on Windows:

在此处输入图片说明

Problem is, that is not where OS HW 2.docx is located. Rather, it's actually located in C:\\Users\\Wade\\Dropbox\\School\\Fall 2018\\IT344\\HW2\\OS HW 2.docx , as seen in the screenshot below: 在此处输入图片说明 There is not another instance of OS HW 2.docx in the root directory of C:\\Users\\Wade , as Python shell seems to indicate.

Where am I going wrong in my code? Is there a more accurate alternative to os.path.abspath() ?

os.walk返回的元组中的files列表仅包含文件名,而不包含路径名,因此在调用os.path.abspath之前,应将其与路径名结合起来:

print os.path.abspath(os.path.join(root, file))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM