Python - WindowsError: [Error 2] the system could not find the file specified: ... afterusign os.path.getsize

StackOverflow https://stackoverflow.com/questions/21894476

Frage

import os
import sys
rootdir = sys.argv[1]
print os.path.abspath(rootdir)

with open('output.txt','r') as fout:
    for root, subFolders, files in os.walk(rootdir):
        for file in files:
        path = os.path.abspath(file)
        print path
        print os.path.getsize(path)
War es hilfreich?

Lösung

os.walk returns a list, one entry for each directory in the directory tree traversal. Each list element contains three elements, the first being the directory name, the second the names of subdirectories and the third the names of files in that directory. These names are only the filenames, not the full or relative paths. So by calling os.path.abspath you are concatenating the filename to the working directory instead of the actual directory the file was found in during traversal. Concatenate the filename with the directory it was found in instead:

import os
import sys
rootdir = sys.argv[1]
print os.path.abspath(rootdir)

with open('output.txt','r') as fout:
    for root, subFolders, files in os.walk(rootdir):
        for file in files:
            path = os.path.join(root, file)
            print path
            print os.path.getsize(path)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top