संभव डुप्लिकेट:
How to identify whether a file is normal file or directory using pythonयह जांचने के लिए कि कोई फ़ाइल निर्देशिका या पाइथन में नियमित फ़ाइल है या नहीं?
आप अगर एक रास्ता अजगर में एक निर्देशिका या फ़ाइल है जांच कैसे करूं?
संभव डुप्लिकेट:
How to identify whether a file is normal file or directory using pythonयह जांचने के लिए कि कोई फ़ाइल निर्देशिका या पाइथन में नियमित फ़ाइल है या नहीं?
आप अगर एक रास्ता अजगर में एक निर्देशिका या फ़ाइल है जांच कैसे करूं?
पाइथन निर्देशिका कार्यों में से कई os.path
module में हैं।
import os
os.path.isdir(d)
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
उपयोग os.path.isdir(path)
अधिक जानकारी के लिए यहाँ http://docs.python.org/library/os.path.html
यदि मैं यह निर्धारित करने के लिए इसका उपयोग करता हूं कि कुछ * फ़ाइल * है, तो क्या होगा यदि 'पथ' की बात एक प्रतीकात्मक लिंक है? – alex
stat प्रलेखन से शैक्षणिक उदाहरण:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)
सबसे सुंदर समाधान नहीं है, लेकिन यदि आपके पास पहले से ही एक स्टेट स्ट्रक्चर है, तो यह आपको os.path.isfile या दोस्तों के माध्यम से अतिरिक्त सिस्टम कॉल/डिस्क खोजने से बचने की अनुमति देता है। –
यदि आप पूर्ण पथ का उपयोग नहीं कर रहे हैं, उदाहरण की तरह , यह केवल स्क्रिप्ट निर्देशिका में "बॉब" अस्तित्व की जांच करेगा (या कहां पाइथन वर्तमान में फाइल सिस्टम में स्थित है) – Matthias