Modify text file with Oracle PL/SQL

oracleplsqlstored-procedures

I'm trying to open and replace a string in a text file with the following procedure:

BEGIN
v_file_name := 'text_file.txt';
v_filehandle := utl_file.fopen(v_file_dir, v_file_name, 'W');
v_id_nextval := v_id_nextval + 1;
BEGIN
LOOP
    utl_file.get_line(v_filehandle, v_new_line);
    v_new_line := replace(v_new_line, 30690, v_id_nextval);
    EXIT WHEN v_new_line IS NULL;
  END LOOP;
END;
utl_file.fclose(v_filehandle);

The problem is that after this procedure runs, the text file becomes empty.
If I replace the 'W' by 'R' in the

v_filehandle := utl_file.fopen(v_file_dir, v_file_name, 'W');

The value of the variable is replaced correctly, but there are no changes made in the text file, because it has only read access.

Am I doing something wrong or is it not possible at all?

PS: I'm using Oracle 9i.

Regards.

Best Answer

Yes, 'W' will do that -- replace the file. Use 'A' to append. I don't think you can "modify in place"; you might have to copy the file to a new one making the changes you desire, delete the original and then rename the copy.

All of this begs the question why you're trying to do all of this in PL/SQL. It might be better -- certainly easier -- to do it in an external program written in eg Python and invoke that.