1
import os
from os import stat
from pwd import getpwuid

searchFolder = raw_input("Type in the directory you wish to search e.g \n /Users/bubble/Desktop/ \n\n\n")
resultsTxtLocation = raw_input("FIBS saves the results in a txt file. Where would you like to save results.txt? \nMust look like this: /users/bubble/desktop/workfile.txt \n\n\n") 

with open(resultsTxtLocation,'w') as f:
    f.write('You searched the following directory: \n' + searchFolder + '\n\n\n')
    f.write('Results for custom search: \n\n\n')
        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
                    print stat(searchFolder).st_uid
                    print getpwuid(stat(searchFolder).st_uid).pw_name
                    f.write('UID: \n'.format(stat(searchFolder).st_uid))
                    f.write('{}\n'.format(pathName))
                    f.write('Size in Bytes: {}\n\n'.format(os.path.getsize(pathName)))

我在这条线上遇到了麻烦:

f.write('UID: \n'.format(stat(searchFolder).st_uid))

我不知道 '{}\n'.format 是做什么的,但有人在上一个问题中提出了建议,所以我认为它可以在这里工作,但它没有。

在输出文本文件中,我得到以下内容:

UID:/Users/bubble/Desktop/Plot 2.docx 字节大小:110549

但它应该说:UID:501

如何让 f.write 理解两个参数并将其写入 txt 文件?

非常感谢

4

2 回答 2

2

改变

f.write('UID: \n'.format(stat(searchFolder).st_uid))
f.write('{}\n'.format(pathName))
f.write('Size in Bytes: {}\n\n'.format(os.path.getsize(pathName)))

进入

f.write('UID: {0}\n'.format(stat(searchFolder).st_uid))
f.write('{0}\n'.format(pathName))
f.write('Size in Bytes: {0}\n\n'.format(os.path.getsize(pathName)))

查看这个答案并进入python 文档以了解字符串格式。

于 2013-07-22T12:46:16.343 回答
2

'UID: {}\n'.format(stat(searchFolder).st_uid). 如果没有{},它只是返回{}: \n

这是字符串格式。{}代表一个替换字段。您可以阅读文档

于 2013-07-22T12:47:20.407 回答