SORU
6 ŞUBAT 2010, CUMARTESİ


Python özyinelemeli klasör oku

N-C arka plan /C ve Python (yaklaşık bir saat yazıyor) keşfetmek duyuyorum. Özyinelemeli olarak bir klasör yapısı metin dosyaları içeriğini okumak için bir komut dosyası yazıyorum.

Yazdığım kodu var sorun sadece tek bir klasör için derin çalışır. Kod (#hardcoded path), ben sadece benim deneyim sadece yeni olduğu için ileri Python ile devam edebilirim bilmiyorum neden görebilirsiniz.

Kod Python:

import os
import sys

rootdir = sys.argv[1]

for root, subFolders, files in os.walk(rootdir):

    for folder in subFolders:
        outfileName = rootdir   "/"   folder   "/py-outfile.txt" # hardcoded path
        folderOut = open( outfileName, 'w' )
        print "outfileName is "   outfileName

        for file in files:
            filePath = rootdir   '/'   file
            f = open( filePath, 'r' )
            toWrite = f.read()
            print "Writing '"   toWrite   "' to"   filePath
            folderOut.write( toWrite )
            f.close()

        folderOut.close()

CEVAP
6 ŞUBAT 2010, CUMARTESİ


os.walk: üç dönüş değerleri anladığınızdan emin olun

for root, subdirs, files in os.walk(rootdir):

şu anlamı var:

  • root: Mevcut yol "ile" doğru yürüdüm
  • subdirs: türü dizini root Dosyaları
  • files: dizin başka tür root Dosyaları (subdirs)

Ve lütfen bir eğik çizgi ile bitiştirmek yerine os.path.join kullanın! Senin sorunun filePath = rootdir '/' file - şu anda "" klasörü yerine en üstteki klasör. yürüdü bağlamak gerekir. filePath = os.path.join(root, file) olmalı. BTW "yerleşik, normalde değişken adı olarak kullanmayın" dosyası

Başka bir sorun, örneğin bu gibi olmalıdır, hangi döngüler vardır:

import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = '   walk_dir)

# If your current working directory may change during script execution, it's recommended to
# immediately convert program arguments to an absolute path. Then the variable root below will
# be an absolute path as well. Example:
# walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = '   os.path.abspath(walk_dir))

for root, subdirs, files in os.walk(walk_dir):
    print('--\nroot = '   root)
    list_file_path = os.path.join(root, 'my-directory-list.txt')
    print('list_file_path = '   list_file_path)

    with open(list_file_path, 'wb') as list_file:
        for subdir in subdirs:
            print('\t- subdirectory '   subdir)

        for filename in files:
            file_path = os.path.join(root, filename)

            print('\t- file %s (full path: %s)' % (filename, file_path))

            with open(file_path, 'rb') as f:
                f_content = f.read()
                list_file.write(('The file %s contains:\n' % filename).encode('utf-8'))
                list_file.write(f_content)
                list_file.write(b'\n')

Eğer haberin yoksa, dosyalar için with ifade bir kısaltma

with open('filename', 'rb') as f:
    dosomething()

# is effectively the same as

f = open('filename', 'rb')
try:
    dosomething()
finally:
    f.close()

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • boniver

    boniver

    17 NİSAN 2006
  • ghosti66

    ghosti66

    27 AĞUSTOS 2006
  • Slave Boy Films - Fandom from a Galaxy Far Far Away

    Slave Boy Fi

    12 HAZİRAN 2009