簡體   English   中英

檢查共享網絡驅動器中是否存在文件

[英]Check if file exists in shared network drive

我試圖確定共享網絡驅動器上是否存在目錄。

import os

if(os.path.exists('/Volumes')):
 print 'path exists'
else:
 print 'path does not exist'

這可以正常工作,但是在傳遞以下參數時失敗:'/ Volumes / A21 \\'s \\ Public \\ Folder'

這對我來說很有意義,因為在我在Finder上打開共享驅動器之前,它不存在。 所以我想我需要先安裝,這是我先從命令行嘗試過的-

mount_smbfs smb://guest@server/A21's Public Folder

這失敗了,所以我不確定os.path.exists參數要傳遞什么。 理想情況下,我希望能夠先掛載到/ Volumes / A21的公用文件夾,然后再檢查該文件夾是否存在?

問題可能出在您復制和粘貼字符串。 我以前有這個問題。 處理文件路徑時,最好使用os join,這樣您遇到的問題就更少

嘗試使用:

os.path.join

例如:

import os

pathtodrive = os.path.join("Volumes", "A21's Public Folder")

if (os.path.exists(pathtodrive)):
    print 'path exists'
else:
    print 'path does not exist'

Python您將執行與在Bash安裝共享中基本相同的例程:

#!/usr/bin/python

import os

home = os.path.expanduser("~")
mnt = home + "/mnt"

if not os.path.exists(mnt): os.makedirs(mnt)
os.chdir(mnt)

os.system("mount_smbfs //username@server._smb._tcp.local/share " + mnt)

這是在用戶主目錄中將掛載點設置為mnt 如果該文件夾不存在,那么它將創建它。 然后,命令切換到該目錄並掛載smb 您需要輸入密碼,或者如果您想使用一種真正不安全的方式,那么您始終可以在命令中包含該密碼(例如, username:password )。

掛載共享后,您可以檢查文件是否存在:

os.path.exists(mnt + "/path/to/file")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM