简体   繁体   中英

Python - f.write 1 arguments, 2 given

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)))

I'm having trouble with this line:

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

I don't know what '{}\\n'.format does, but someone suggested it in a previous question, so I thought it'd work here, but it doesn't.

Inside the output text file, I just get the following:

UID: /Users/bubble/Desktop/Plot 2.docx Size in Bytes: 110549

But it should say: UID: 501

How can I make the f.write understand two arguments and write it into the txt file?

many thanks

change

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)))

into

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 and into python documentation to learn about string formatting.

'UID: {}\\n'.format(stat(searchFolder).st_uid) . If there is no {} , it just returns {}: \\n .

This is string format. The {} represents a replacement fields. You may read the doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM