[英]How to write last 50 lines from one file to another Python
I am creating an email response to an overnight build, I want to get the last 50 lines from the results file and place it into a summary file. 我正在为隔夜版本创建电子邮件回复,我想从结果文件中获取最后50行并将其放入摘要文件中。 The code that I have done is below, can anyone help?
我所做的代码如下,有人可以帮忙吗?
def email_success():
fp = open(results_file, 'r')
sum_file = (fp.readlines()[-50:])
fp.close()
myfile = open(result_summary,'w')
myfile.write(sum_file)
myfile.close()
I have got the error message below when trying this code: 尝试以下代码时,我收到以下错误消息:
Traceback (most recent call last):
File "email_success.py", line 76, in <module>
if __name__ == '__main__': myObject = email_success()
File "email_success.py", line 45, in email_success
myfile = open(result_summary,'w')
TypeError: coercing to Unicode: need string or buffer, tuple found
Thanks 谢谢
The results summary is a variable that stores an address. 结果摘要是存储地址的变量。
result_summary = (t, 'results_summary.txt')
Sorry made a stupid mistake, I forgot to add os.path.join 抱歉犯了一个愚蠢的错误,我忘了添加os.path.join
result_summary = os.path.join(t, 'results_summary.txt')
Thanks for the help 谢谢您的帮助
@alok It is a directory address, I forgot to add the os.join to make it one string. @alok这是一个目录地址,我忘记添加os.join使其成为一个字符串。 This is what was causing the error
这是导致错误的原因
TypeError: coercing to Unicode: need string or buffer, tuple found
Error says its expect string or buffer but you are passing tuple
, so just join it with ""
to make it to string 错误指出其期望的字符串或缓冲区,但是您正在传递
tuple
,因此只需将其与""
连接起来即可使其成为字符串
So, Try 所以,尝试
sum_file = "".join(fp.readlines()[-50:])
UPDATE : because OP updated the question UPDATE :因为OP更新了问题
if result_summary = (t, 'results_summary.txt')
如果
result_summary = (t, 'results_summary.txt')
Try 尝试
myfile = open(result_summary[1],'w')
它是open()引发异常,但是...您如何定义result_summary?
result_summary
is a tuple, it needs to be either a str
or buffer. result_summary
是一个元组,它必须是str
或buffer。 Your explanation has nothing to do with the error you posted. 您的解释与您发布的错误无关。
result_summary = (t, 'results_summary.txt')
and 和
myfile = open(result_summary,'w')
means 手段
myfile = open((t, 'results_summary.txt'),'w')
which obviously won't work, try: 显然不起作用,请尝试:
myfile = open(result_summary[1],'w')
instead 代替
fp.readlines()
method returns a list of lines. fp.readlines()
方法返回行列表。 Therefore you can't apply [-50:]
operator. 因此,您不能应用
[-50:]
运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.