Python 如何一次迭代或循环?
我想知道是否有人能告诉我缺少什么,因为我想运行一个程序,该程序检查目录中的文件列表,然后在删除之前打印以下内容:Python 如何一次迭代或循环?,python,Python,我想知道是否有人能告诉我缺少什么,因为我想运行一个程序,该程序检查目录中的文件列表,然后在删除之前打印以下内容: 创建、修改时间 名称和扩展名 大小 但是,我无法循环大小和cereated,modified time,它会列出文件,但会显示目录的大小和创建,修改时间 import os.path, time, fnmatch # get file info including time def get_File_Info(): print("Last modified: %
import os.path, time, fnmatch
# get file info including time
def get_File_Info():
print("Last modified: %s" % time.ctime(os.path.getmtime('my file path')))
print("Created: %s" % time.ctime(os.path.getctime('my file path')))
#get file size
def get_File_Size():
file_size = os.stat('my file path')
print("Size of file :", file_size.st_size, "bytes")
# Get file name and Extension
for file_name in os.listdir('my file path'):
if fnmatch.fnmatch(file_name, '*.*'):
print(file_name)
print(get_File_Info())
print(get_File_Size())
函数需要将文件路径名作为参数
import os, time, glob
# get file info including time
def get_File_Info(filename):
print("Last modified: %s" % time.ctime(os.path.getmtime(filename)))
print("Created: %s" % time.ctime(os.path.getctime(filename)))
#get file size
def get_File_Size(filename):
file_size = os.stat(filename)
print("Size of file :", file_size.st_size, "bytes")
# Get file name and Extension
for file_name in glob.glob('my file path/*.*'):
print(os.path.basename(file_name))
get_File_Info(file_name)
get_File_Size(file_name)
您还可以使用glob.glob()
仅获取与模式匹配的文件名列表,而不是将os.listdir()
与fnmatch.fnmatch()
混合使用
您也不应该打印
get_XXX
函数的结果,因为这些函数自己打印,不返回任何内容。如果您总是以'my file path'
作为参数调用函数,那么您将得到相同的结果。如果您想获取有关不同文件的信息,需要将其作为参数传递,而不是目录名。我认为您应该将os.path.join('my file path',file_name)
作为参数传递给函数,然后使用该路径获取ctime/mtime/size。噢,谢谢打印(“创建的:%s”%time.ctime(os.path.getctime(filename))
仍然显示文件目录而不是单个文件,不知道为什么