我需要帮助,有人可以指导我如何在python中编写一个脚本,它将挂载点作为参数并返回挂载点上所有文件的列表及其以json格式的字节数的磁盘使用情况
脚本输出示例: -
getdiskusage.py /tmp
{
"files":
[
{"/tmp/foo", 1000},
{"/tmp/bar", 1000000},
{"/tmp/buzzz", 42},
],
}
答案 0 :(得分:0)
def getListOfFiles(dirName):
try:
listOfFile = os.listdir(dirName)
allFiles = list()
for entry in listOfFile:
fullPath = os.path.join(dirName, entry)
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
return allFiles
except(FileNotFoundError):
print("file not found")
return 1
def main():
dirName = sys.argv[1]
listOfFiles = getListOfFiles(dirName)
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(dirName):
listOfFiles += [os.path.join(dirpath, file) for file in filenames]
print("{ \"files:\" [")
for elem in listOfFiles:
print("{\"",elem,"\"", ",",os.path.getsize(elem),"},")
print("],}")
if __name__ == '__main__':
main()
答案 1 :(得分:-1)
虽然你还没有提到,到目前为止你尝试了什么,但你可以从下面的代码开始 -
d
可能会有更多优化,您还需要考虑以json格式获取此信息。