Python os走到文本文件?只打印一行

时间:2013-07-22 06:52:28

标签: python output

import os

searchFolder = '/Users/bubble/Desktop/pics'


for root, dirs, files in os.walk(searchFolder):
    for file in files:
        pathName = os.path.join(root,file)
        print pathName
        print os.path.getsize(pathName)
        print 
        f = open('/Users/bubble/Desktop/workfile.txt','w')
        f.write(pathName) 

只有一行打印到文本文件:/Users/bubble/Desktop/pics/IMG_2999.JPG

我希望将整个输出打印到一个文本文件中(可能以后,甚至是我可以编辑的html文件看起来很漂亮)

由于

1 个答案:

答案 0 :(得分:2)

你正在循环覆盖文件。打开一次。

import os

searchFolder = '/Users/bubble/Desktop/pics'

with open('/Users/bubble/Desktop/workfile.txt','w') as f:
    for root, dirs, files in os.walk(searchFolder):
        for file in files:
            pathName = os.path.join(root,file)
            print pathName
            print os.path.getsize(pathName)
            print
            f.write('{}\n'.format(pathName))
            f.write('{}\n'.format(os.path.getsize(pathName)))