2

I have a python code like this:

with open('myFile') as f:
        next(f) # skip first line
        for line in f:
            items = line.split(';')
            if len(items) < 2:
                # now I want to replace the line with s.th. that i write

how to replace the line with s.th. that I want to write?

gurehbgui
  • 14,236
  • 32
  • 106
  • 178

2 Answers2

6

Use the fileinput module's inplace functionality. Refer Optional in-place filtering section at fileinput. Something like this:

import fileinput
import sys
import os

for line_number, line in enumerate(fileinput.input('myFile', inplace=1)):
  if line_number == 0:
    continue
  items = line.split(';')
  if len(items) < 2:
    sys.stdout.write('blah' + os.linesep)
  else:
    sys.stdout.write(line)
iruvar
  • 22,736
  • 7
  • 53
  • 82
1

Open file in r+ mode, read it's content in a list first and then after truncation you can write the new data back to the file.

'r+' opens the file for both reading and writing

If the file is huge then it is better to write this to new file first and then rename.

with open('myFile','r+') as f:
        data=f.readlines()[1:]
        f.truncate(0)          #this will truncate the file
        f.seek(0)             #now file pointer goes to start of the file
        for line in data:     #now write the new data
            items = line.split(';') 
            if len(items) < 2:
                # do something here
            else:
                f.write(line)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504