【发布时间】:2014-07-04 13:27:25
【问题描述】:
我卡住了。我需要使用 Python 编写代码来按文件大小查找文件并将其名称和大小添加到列表中。我有一个程序,它按名称在目录中搜索文件。我需要使用 get opts 制作另一个标志以按大小进行搜索。
import getopt
import sys
import os
from os import listdir, walk
from os.path import isfile, join
def find_by_name(name, path, result): #Define a function to search the file by it's name
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(name)) #Join the file to the list called result
else:
print ("Nothing was found by %s" % name)
return result
def main():
path_dir = raw_input("Select the directory you want to search: ")
results = []
try:
opts, args = getopt.getopt(sys.argv[1:], 'n:y:d:')
except getopt.GetoptError as err:
print (err)
sys.exit
for o, a in opts:
if o in ("-n", "--name"):
pro = find_by_name(a, path_dir, results)
if __name__ == "__main__":
main()
【问题讨论】:
-
我觉得这是一个很好的主题问题,但由于提问者不熟悉英语,因此很难解析。有人可以翻译吗?
-
他想要文件的大小
-
您可以使用 [此处][1] [1] 中所述的 os.stat 函数查找文件大小:stackoverflow.com/questions/2104080/…
-
@AdamSmith 我只是想按文件大小解析文件,就像使用函数 find_by_name 一样。对不起我的英语不好:)
-
@user3642703 无需为你的英语不好而道歉——我可以保证你说我的语言比我说你的好!