我正在编写一个简单的Python脚本,告诉我从CSV导入的一组文档的文件大小。我验证了所有条目都不超过100个字符,因此此错误“ ValueError:scandir:Windows的路径太长”对我来说没有道理。
这是我的代码:
# 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)
据我了解,Windows中的最大路径大小为260个字符,因此1个驱动程序字母+ 100个字符的路径不应超过Windows的最大长度。
以下是路径的示例:“ / Document / 8669 / CORRESP / 1722165.doc”
答案 0 :(得分:1)
您要尝试folder
使用的walk
字符串会永远增长。将代码简化为问题区域:
folder = "S:"
# Exporting outcome
for list1 in list1:
folder = folder + str(list1)
您永远不会设置folder
,因此它以S:<firstpath>
开头,然后在下一个循环中依次为S:<firstpath><secondpath>
,然后是S:<firstpath><secondpath><thirdpath>
,以此类推。简单修复:单独的驱动器来自folder
:
drive = "S:"
# Exporting outcome
for path in list1:
folder = drive + path
现在folder
是在每个循环中从头开始构建的,丢弃了先前的路径,而不是将它们串联在一起。
我还给了迭代值一个有用的名称(并删除了str
调用,因为这些值都应该已经是str
了。)