读/写文本文件

发布于 2021-01-29 14:59:47

我正在尝试更改文本文件中的某些行,而不影响其他行。这就是文本文件“ text.txt”中的内容

this is  a test1|number1
this is a test2|number2
this is a test3|number2
this is a test4|number3
this is a test5|number3
this is a test6|number4
this is a test7|number5
this is a test8|number5
this is a test9|number5
this is a test10|number5

我的目标是更改第4行和第5行,但其余部分保持不变。

mylist1=[]
for lines in open('test','r'):
    a=lines.split('|')
    b=a[1].strip()
    if b== 'number3':
        mylist1.append('{}|{} \n'.format('this is replacement','number7'))
    else:
         mylist1.append('{}|{} \n'.format(a[0],a[1].strip()))
myfile=open('test','w')
myfile.writelines(mylist1)

即使代码有效,我想知道是否有更好,更有效的方法?是否可以仅通过行号读取文件?

关注者
0
被浏览
90
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您没有什么可以改善的。但是您必须将所有行都写入 一个新文件 ,无论已更改还是未更改。较小的改进将是:

    • 使用该with语句;
    • 避免将行存储在列表中;
    • 子句中lines不带格式书写else(如果适用)。

    应用以上所有内容:

    import shutil
    with open('test') as old, open('newtest', 'w') as new:
        for line in old:
            if line.rsplit('|', 1)[-1].strip() == 'number3':
                new.write('this is replacement|number7\n')
            else:
                new.write(line)
    shutil.move('newtest', 'test')
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看