简体   繁体   中英

Write string and variables to file in python

I am trying to write a line to text file in python with below code but its giving me an error

logfile.write('Total Matched lines : ', len(matched_lines))

i know we cannot give 2 arguments for .write but whats the right way to do it. Any help is appreciated.

Turn it into one argument, such as with the newish format strings:

logfile.write(f'Total Matched lines : {len(matched_lines)}\n')

Or, if you're running a version before where this facility was added (3.6, I think), one of the following:

logfile.write('Total Matched lines : {}\n'.format(len(matched_lines)))
logfile.write('Total Matched lines : ' + str(len(matched_lines)) + '\n')

Aside: I've added a newline since you're writing to a log file (most likely textual) and write does not do so. Feel free to ignore the \\n if you've made the decision to not write it on an individual line.

Try:

logfile.write('Total Matched lines : {}'.format(len(matched_lines)))

or:

logfile.write('Total Matched lines : %d' % len(matched_lines))

You could say:

logfile.write('Total matches lines: ' + str(len(matched_lines)))

Or:

logfile.write('Total matches lines: {}'.format(len(matched_lines)))

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