在python中查找和打印零长度文件的文件名 [英] Finding and printing file name of zero length files in python

查看:199
本文介绍了在python中查找和打印零长度文件的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习os模块,我需要解决的问题是仅打印零长度文件的文件名和计数.

I'm learning about the os module and I need to work out to print the file names of only zero length files and the count.

到目前为止,我已经想到最简单的方法是以这种格式生成文件列表或元组及其大小:

So far I've figured the easiest way to do it is to generate a list or a tuple of files and their sizes in this format:

(((zerotextfile1.txt,0),(notazerotextfile.txt,15))

((zerotextfile1.txt, 0), (notazerotextfile.txt, 15))

然后使用if语句仅打印出长度为零的文件.

Then use an if statement to only print out only files with zero length.

然后使用求和功能将列表项的数量相加以获得零长度文件的计数.

Then use a sum function to add the number of list items to get the count of zero length files.

到目前为止,我有很多零碎的东西,这是我遇到麻烦时如何将它们放在一起的方式.

So far, I've got bits and pieces - it's how to put them together I'm having trouble with.

我的一些东西(我设法编写的可行代码,我知道不多):

Some of my bits (viable code I've managed to write, not much, I know):

import os
place = 'C:\\Users\\Me\\Documents\\Python Programs\\'
for files in os.walk(place):
    print (files)

然后有诸如os.path.getsize()之类的东西,需要我输入文件名,所以我认为我必须使用for循环在此函数中打印文件名列表,以便获取它可以工作,对吧?

Then there is stuff like os.path.getsize() which requires I put in a filename, so I figure I've got to use a for loop to print a list of the file names in this function in order to get it to work, right?

任何提示或指向正确的方向将不胜感激!

Any tips or pointing in the right direction would be vastly appreciated!

推荐答案

import os
place = 'C:\\Users\\Me\\Documents\\Python Programs\\'
for root, dirs, files in os.walk(place):
    for f in files:
        file_path = os.path.join(root, f) #Full path to the file
        size = os.path.getsize(file_path) #pass the full path to getsize()
        if size == 0:
            print f, file_path

这篇关于在python中查找和打印零长度文件的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆