1

Linuxシステムの各サブディレクトリにあるファイル数の概要をExcelシートにまとめようとしています。

ディレクトリは通常、次のように設定されますmaindir/person/task/somedata/files。ただし、設定するサブディレクトリはさまざまです(つまり、一部のファイルには' task'ディレクトリがない場合があります)。そのため、Pythonにファイルパスをウォークさせる必要があります。

私の問題は、' person'以降のすべてのサブディレクトリ名が必要であり、現在、私のコード(以下)はファイル数で最も近いディレクトリのみをアタッチしていることです。誰かが私がこれを理解するのを手伝ってくれるなら、それは大いにありがたいです!

import os, sys, csv

outwriter = csv.writer(open("Subject_Task_Count.csv", 'w'))

dir_count=[]
os.chdir('./../../')
rootDir = "./" # set the directory you want to start from
for root, dirs, files in os.walk( rootDir ):
for d in dirs:
    a = str(d)
    count = 0
    for f in files:
        count+=1
    y= (a,count)
    dir_count.append(y)

for i in dir_count:
    outwriter.writerow(i)
4

2 に答える 2

4

次の行に沿って何かを試す必要があります。

for root,dirs,files in os.walk( rootDir ) :
    print root, len(files)

サブディレクトリとファイル数を出力します。

于 2012-11-21T23:01:03.090 に答える
0

あなたの質問がよくわかりませんでした。os.walk のドキュメントを読み直してください。 rootトラバースされている現在のディレクトリです。 dirsは の直下のサブディレクトリでrootfilesは の直下にあるファイルですroot。コードが (ルートから) 同じファイルをカウントし、各サブディレクトリ内のファイル数として記録するようになりました。

これが私が思いついたものです。うまくいけば、それはあなたが望むものに近いです. そうでない場合は、適応してください:) ディレクトリ、ディレクトリ内のファイル数、およびディレクトリとそのすべてのサブディレクトリ内のファイル数を出力します。

import os
import csv

# Open the csv and write headers.
with open("Subject_Task_Count.csv",'wb') as out:
    outwriter = csv.writer(out)
    outwriter.writerow(['Directory','FilesInDir','FilesIncludingSubdirs'])

    # Track total number of files in each subdirectory by absolute path
    totals = {}

    # topdown=False iterates lowest level (leaf) subdirectories first.
    # This way I can collect grand totals of files per subdirectory.
    for path,dirs,files in os.walk('.',topdown=False):
        files_in_current_directory = len(files)

        # Start with the files in the current directory and compute a
        # total for all subdirectories, which will be in the `totals`
        # dictionary already due to topdown=False.
        files_including_subdirs = files_in_current_directory
        for d in dirs:
            fullpath = os.path.abspath(os.path.join(path,d))

            # On my Windows system, Junctions weren't included in os.walk,
            # but would show up in the subdirectory list.  this try skips
            # them because they won't be in the totals dictionary.
            try:
                files_including_subdirs += totals[fullpath]
            except KeyError as e:
                print 'KeyError: {} may be symlink/junction'.format(e)

        totals[os.path.abspath(path)] = files_including_subdirs
        outwriter.writerow([path,files_in_current_directory,files_including_subdirs])
于 2012-11-21T23:44:04.430 に答える