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文件?
非常感谢答案 0 :(得分: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)))
Look at this answer和python documentation以了解字符串格式。
答案 1 :(得分:2)
'UID: {}\n'.format(stat(searchFolder).st_uid)
。如果没有{}
,则只返回{}: \n
。
这是字符串格式。 {}
代表替换字段。您可以阅读doc。