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?

4

2 回答 2

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)
于 2013-04-25T13:52:39.863 回答
1

以模式打开文件r+,首先读取列表中的内容,然后在截断后将新数据写回文件。

'r+' 打开文件进行读写

如果文件很大,最好先将其写入新文件,然后重命名。

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)
于 2013-04-25T13:58:30.463 回答