Python Forum
Updating a filesets contents
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating a filesets contents
#1
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.
Reply
#2
Hello!

Did you tried f.seek(0, 0)?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(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 ??
Reply
#4
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)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020