Alexander Babenchuk
Alexander Babenchuk

Reputation: 23

ValueError: scandir: path too long for Windows

I am writing a simple Python script to tell me file size for a set of documents which I am importing from a CSV. I verified that none of the entries are over 100 characters, so this error "ValueError: scandir: path too long for Windows" does not make sense to me.

Here is my code:

# determine size of a given folder in MBytes
import os, subprocess, json, csv, platform

# Function to check if a Drive Letter exists
def hasdrive(letter):
    return "Windows" in platform.system() and os.system("vol %s: 2>nul>nul" % (letter)) == 0

# Define Drive to check for
letter = 'S'

# Check if Drive doesnt exist, if not then map drive
if not hasdrive(letter):
    subprocess.call(r'net use s: /del /Y', shell=True)
    subprocess.call(r'net use s: \\path_to_files', shell=True)

list1 = []
# Import spreadsheet to calculate size
with open('c:\Temp\files_to_delete_subset.csv') as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        list1.extend(row)

# Define variables
folder = "S:"
folder_size = 0

# Exporting outcome
for list1 in list1:
    folder = folder + str(list1)
    for root, dirs, files in os.walk(folder):
        for name in files:
            folder_size += os.path.getsize(os.path.join(root, name))
            print(folder)
            # print(os.path.join(root, name) + " " + chr(os.path.getsize(os.path.join(root, name))))

print(folder_size)

From my understanding the max path size in Windows is 260 characters, so 1 driver letter + 100 character path should NOT exceed the Windows max.

Here is an example of a path: '/Document/8669/CORRESP/1722165.doc'

Upvotes: 1

Views: 1660

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155333

The folder string you're trying to walk is growing forever. Simplifying the code to the problem area:

folder = "S:"

# Exporting outcome
for list1 in list1:
    folder = folder + str(list1)

You never set folder otherwise, so it starts out as S:<firstpath>, then on the next loop it's S:<firstpath><secondpath>, then S:<firstpath><secondpath><thirdpath>, etc. Simple fix: Separate drive from folder:

drive = "S:"

# Exporting outcome
for path in list1:
    folder = drive + path

Now folder is constructed from scratch on each loop, throwing away the previous path, rather than concatenating them.

I also gave the iteration value a useful name (and removed the str call, because the values should all be str already).

Upvotes: 1

Related Questions