Python Forum

Full Version: Updating a filesets contents
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a number of files that are to be used for transcription purposes and they all need modifying. The code is nearly working, but it is duplicating the content, rather than replacing the content.

#!/usr/bin/python

import glob, os
os.chdir("/home/*******/somepath")

for file in glob.glob("chunk*.txt"):
    print(file)
    f = open(file, 'r+')
    next = f.readline()
    while next != "":
        print(next)
        newline = "</s>" + next + "</s>"
        #f.seek(0)
        f.write(newline) #write updated line
        next = f.readline()
    # Close file
    f.close()
All the files needed are called chunk*.txt, they are then opened and updated. Here is one file content befpre the code is run ..

Quote:chunk-142.txt
No the outcome will be completely different

and after the script has run

Quote:chunk-142.txt
No the outcome will be completely different</s>No the outcome will be completely different</s>

I did try using the seek() command, but it produced a lot of garbage.
Hello!

Did you tried f.seek(0, 0)?
(Mar-10-2018, 11:52 AM)wavic Wrote: [ -> ]Did you tried f.seek(0, 0)?

Yes, tried that. It produces more output (not less) and goes into a loop ??
This is working okay.

#!/usr/bin/python3

import glob, os
os.chdir("/home/somepath")

for file in glob.glob("chunk*.txt"):
    print(file)
    open_file = open(file,'r')
    read_file = open_file.read()
    read_file = "<s> " + read_file + " </s> " + "(" + (file.replace(".txt" , ".wav" , 4))  + ")"
    write_file = open(file,'w')
    write_file.write(read_file)

    # Close file
    open_file.close()
Quote:chunk142.txt
<s> No the outcome will be completely different </s> (chunk-142.wav)