2

i have an input file that goes something like this:

blah blah
blah blah ;blah blah
blah blah ;blah blah
blah 

What my program does is split the lines when it sees a semicolon and goes to the next line which is what i want it to do (i want it to ignore the semicolon bits) producing something like this:

blah blah
blah blah
blah blah
blah

however when it writes to the file it appends the new code to the old, and i just want to have the new code in the file. Is there any way this can be done? Thank You.

f = open ('testLC31.txt', 'r+')
def after_semi(f):
    for line in f:
        yield line.split(';')[0]       


for line in after_semi(f):
    f.write('!\n' + line)  

f.close()
Chalupa
  • 367
  • 1
  • 5
  • 20

2 Answers2

0

When you are opening the file, the r+ tells Python to append to the file. It sounds like you want to overwrite the file. The w+ flag will do that for you, see Python docs on open()

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file.

f = open ('testLC31.txt', 'w+')
def after_semi(f):
    for line in f:
        yield line.split(';')[0]       

for line in after_semi(f):
    f.write('!\n' + line)  

f.close()

I'd suggest using with to ensure the file always gets closed, this should point you in the right direction:

with open ('testLC31.txt', 'w+') as fout:
    for line in after_semi(f):
        fout.write('!\n' + line) 

Hope it helps!

Donovan Solms
  • 941
  • 12
  • 17
  • 1
    thanks, i tried that but it just gives me an empty file – Chalupa Feb 10 '15 at 05:35
  • Oh wait, the `w+` flag truncates the file you open, so if you are writing to the same file you are reading from the `testLC31.txt` file will not contain the `blah;blah` text. I misunderstood a that bit. – Donovan Solms Feb 10 '15 at 05:39
0

I would use re.sub like below,

import re
f = open('file', 'r')                 # Opens the file for reading
fil = f.read()                        # Read the entire data and store it in a variabl.
f.close()                             # Close the corresponding file
w = open('file', 'w')                 # Opens the file for wrting
w.write(re.sub(r';.*', r'', fil))     # Replaces all the chars from `;` upto the last with empty string.
w.close()
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274