简体   繁体   English

读/写文本文件

[英]Read/Write text file

I am trying to change a some lines in a text file without affecting the other lines. 我正在尝试更改文本文件中的某些行,而不影响其他行。 This is what's inside the text file called "text.txt" 这就是文本文件“ 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

My objective is to change the line 4 and line 5 but keep the rest same. 我的目标是更改第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)

Even though the code works, I am wondering if there is any better and efficient way to do it? 即使代码有效,我想知道是否有更好,更有效的方法? Is it possible to read the file just by line number? 是否可以仅通过行号读取文件?

There is not much you can improve. 您没有什么可以改善的。 But you have to write all lines to a new file , either changed or unchanged. 但是您必须将所有行都写入一个新文件 ,无论已更改还是未更改。 Minor improvements would be: 较小的改进将是:

  • using the with statement; 使用with语句;
  • avoiding storing lines in a list; 避免将行存储在列表中;
  • writing lines without formatting in the else clause (if applicable). else子句中编写lines而不进行格式化(如果适用)。

Applying all of the above: 应用以上所有内容:

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

否。文件是面向字节的,而不是面向行的,并且更改行的长度不会使后面的字节超前。

try this solution 试试这个解决方案

with open('test', inplace=True) as text_file:
    for line in text_file:
         if line.rsplit('|', 1)[-1].strip() == 'number3':
             print '{}|{} \n'.format('this is replacement', 'number7')
         else:
             print line

It's not wholly clear whether your intent is to identify the lines to be replaced by their value , or by their line number . 目前尚不清楚您的意图是要识别要替换为它们的或它们的行号

If the former is your intent, you can get a list of lines like this: 如果前者是您的意图,则可以获得以下行的列表:

with open('test','r') as f:
    oldlines = f.read().splitlines()

If there's a danger of trailing whitespace, you could also: 如果存在尾随空格的危险,您还可以:

Then you can process them like this: 然后,您可以像这样处理它们:

newlines = [ line if not line.strip().endswith('|number3') else 'this is replacement|number7' for line in oldlines]

Open the destination file (I'm assuming you want to overwrite the original, here), and write all the lines: 打开目标文件(假设您要在此处覆盖原始文件),并写所有行:

with open('test','w') as f:
    f.write("\n".join(newlines))

This is a general pattern that's useful for any kind of simple line-filtering. 这是一种通用模式,可用于任何类型的简单行过滤。

If you meant to identify the lines by number, you could just alter the 'newlines' line: 如果要通过数字标识行,则可以更改“换行”行:

 newlines = [ line if i not in (3, 4) else 'this is replacement|number7' for i, line in enumerate(oldlines)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM