[英]How to write last 50 lines from one file to another Python
我正在為隔夜版本創建電子郵件回復,我想從結果文件中獲取最后50行並將其放入摘要文件中。 我所做的代碼如下,有人可以幫忙嗎?
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()
嘗試以下代碼時,我收到以下錯誤消息:
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
謝謝
結果摘要是存儲地址的變量。
result_summary = (t, 'results_summary.txt')
抱歉犯了一個愚蠢的錯誤,我忘了添加os.path.join
result_summary = os.path.join(t, 'results_summary.txt')
謝謝您的幫助
@alok這是一個目錄地址,我忘記添加os.join使其成為一個字符串。 這是導致錯誤的原因
TypeError: coercing to Unicode: need string or buffer, tuple found
錯誤指出其期望的字符串或緩沖區,但是您正在傳遞tuple
,因此只需將其與""
連接起來即可使其成為字符串
所以,嘗試
sum_file = "".join(fp.readlines()[-50:])
UPDATE :因為OP更新了問題
如果result_summary = (t, 'results_summary.txt')
嘗試
myfile = open(result_summary[1],'w')
它是open()引發異常,但是...您如何定義result_summary?
result_summary
是一個元組,它必須是str
或buffer。 您的解釋與您發布的錯誤無關。
result_summary = (t, 'results_summary.txt')
和
myfile = open(result_summary,'w')
手段
myfile = open((t, 'results_summary.txt'),'w')
顯然不起作用,請嘗試:
myfile = open(result_summary[1],'w')
代替
fp.readlines()
方法返回行列表。 因此,您不能應用[-50:]
運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.