我有一个文本文件
line0
line1
line2
line3
line4
.....
和xml文件
<names>
<name A </name>
<name B </name>
<name C </name>
<name D </name>
<name E </name>
...............
</names>
我喜欢将第1行向上移动(EX:第2行或名称D向上1行)
line0
line2
line1
line3
line4
.....
<names>
<name A </name>
<name B </name>
<name D </name>
<name C </name>
<name E </name>
...............
</names>
或1行向下(EX:第3行或名称B向下1行)
line0
line1
line2
line4
line3
.....
<names>
<name A </name>
<name C </name>
<name B </name>
<name D </name>
<name E </name>
...............
</names>
如何使用Python完成它?
谢谢。
答案 0 :(得分:0)
使用清单:
def movelineup(filename, linenum):
if linenum == 1 or linenum > len(filename):
return None
filelines = []
f = open('test.txt', 'r+')
for i in range(0, len(filename)):
filelines.append(f.readline())
filelines[linenum - 2], filelines[linenum - 1] =\
filelines[linenum - 1], filelines[linenum - 2]
f.seek(0)
for line in filelines:
f.write(line)
movelineup('test.txt', 3)
line0 # line 1
line2 # line 2
line1 # line 3
line3 # line 4
line4 # line 5