读/写文本fi

2024-06-23 19:55:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在不影响其他行的情况下更改文本文件中的某些行。这是名为“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)

即使代码是有效的,我想知道是否有更好和有效的方法来实现它?是否可以仅按行号读取文件?


Tags: testformatisopenthismyfilestriplines
3条回答
import fileinput

for lines in fileinput.input('test', inplace=True):
    # inplace=True redirects stdout to a temp file which will
    # be renamed to the original when we reach the end of the file. this
    # is more efficient because it doesn't save the whole file into memeory
    a = lines.split('|')
    b = a[1].strip()
    if b == 'number3':
        print '{}|{} '.format('this is replacement', 'number7')
    else:
        print '{}|{} '.format(a[0], a[1].strip())

你没什么可以改进的。但您必须将所有行写入一个新文件,可以是已更改的,也可以是未更改的。小的改进将是:

  • 使用with语句
  • 避免在列表中存储行
  • else子句中不格式化地编写lines(如果适用)。

应用以上所有内容:

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')

不可以。文件是面向字节的,而不是面向行的,更改行的长度不会增加以下字节。

相关问题 更多 >

    热门问题