从文本文件中读取行,反转并保存在新的文本文件中 [英] Read lines from a text file, reverse and save in a new text file
本文介绍了从文本文件中读取行,反转并保存在新的文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止我有这个代码:
So far I have this code:
f = open("text.txt", "rb")
s = f.read()
f.close()
f = open("newtext.txt", "wb")
f.write(s[::-1])
f.close()
原文件中的文字为:
This is Line 1
This is Line 2
This is Line 3
This is Line 4
当它反转并保存它时,新文件看起来像这样:
And when it reverses it and saves it the new file looks like this:
4 eniL si sihT 3 eniL si sihT 2 eniL si sihT 1 eniL si sihT
当我希望它看起来像这样时:
When I want it to look like this:
This is line 4
This is line 3
This is line 2
This is line 1
我该怎么做?
推荐答案
f = open("text.txt", "rb")
s = f.readlines()
f.close()
f = open("newtext.txt", "wb")
s.reverse()
for item in s:
print>>f, item
f.close()
这篇关于从文本文件中读取行,反转并保存在新的文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文