Read/Write text file

后端 未结 5 1738
眼角桃花
眼角桃花 2020-12-20 06:46

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\"

this is  a test         


        
相关标签:
5条回答
  • 2020-12-20 06:54

    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
    
    0 讨论(0)
  • 2020-12-20 07:07

    No. Files are byte-oriented, not line-oriented, and changing the length of a line will not advance the following bytes.

    0 讨论(0)
  • 2020-12-20 07:10

    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)]
    
    0 讨论(0)
  • 2020-12-20 07:13

    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;
    • avoiding storing lines in a list;
    • writing lines without formatting in the else clause (if applicable).

    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')
    
    0 讨论(0)
  • 2020-12-20 07:15
    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())
    
    0 讨论(0)
提交回复
热议问题