Updating a filesets contents - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Updating a filesets contents (/thread-8851.html) |
Updating a filesets contents - jehoshua - Mar-10-2018 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 and after the script has run Quote:chunk-142.txt I did try using the seek() command, but it produced a lot of garbage. RE: Updating a filesets contents - wavic - Mar-10-2018 Hello! Did you tried f.seek(0, 0) ?
RE: Updating a filesets contents - jehoshua - Mar-10-2018 (Mar-10-2018, 11:52 AM)wavic Wrote: Did you tried Yes, tried that. It produces more output (not less) and goes into a loop ?? RE: Updating a filesets contents - jehoshua - Mar-11-2018 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 |