简体   繁体   English

在python中将字符串和变量写入文件

[英]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我试图用下面的代码在 python 中的文本文件中写一行,但它给了我一个错误

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.我知道我们不能为 .write 提供 2 个参数,但正确的方法是什么。 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:或者,如果您在添加此功能之前运行的版本(我认为是 3.6),请执行以下操作之一:

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.旁白:我添加了一个换行符,因为您正在写入日志文件(很可能是文本文件)并且write没有这样做。 Feel free to ignore the \\n if you've made the decision to not write it on an individual line.如果您决定不在单独的行上写它,请随意忽略\\n

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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