0

I got a file, I want to be able to get the content of this file and write them x number of time to another file based on a provided number.

I got this code but I get written the content of my file only one time.....

replace_num_array is my number of time mentioned above.

def replace_lines(f, wf):
    for i, line in enumerate(f, 1):
        wf.write(line)


def copy_cust(f, wf, replace_num_array):
    for y in replace_num_array:
        replace_lines(f, wf)


def process_file(filename, writefile, tagname, rectype_whereTagNameGoes, tagname_whichrec_coordinates_findall, replace_coordinates_findall, replace_num_array):
    with codecs.open(filename, 'r', encoding='utf-8', errors='ignore') as f:
        with open(writefile, 'a+') as wf:
            copy_cust(f, wf, replace_num_array)

Any help is much appreciated, I am pretty new to Python, probably I am doing something quite silly here...

I don't get error with my code but I don't get copy X number of time, I think I am writing over the same contents :-)

Thanks,

Paolo

finnmglas
  • 1,626
  • 4
  • 22
  • 37
  • Each open file has a file pointer to remember where to read or write next. It moves when reading or writing is done. Your file to read from has the pointer at its end after it was read once. – Michael Butscher Jun 11 '20 at 11:30
  • `copy_cust(f, wf, replace_num_array)` reads the file, after it you need to close/reopen it or seek() to its start again. See dupe. – Patrick Artner Jun 11 '20 at 11:31
  • Add the line `f.seek(0)` to the beginning of `replace_lines`. – ekhumoro Jun 11 '20 at 11:38
  • Thanks a lot guys....i understand now..... – Paolo Tagliente Jun 12 '20 at 21:41
  • I ended up going like this actually...it works.....is it decent code you think? the file am opening is small..... – Paolo Tagliente Jun 12 '20 at 21:43
  • def process_file(filename, writefile, tagname, rectype_whereTagNameGoes, tagname_whichrec_coordinates_findall, replace_coordinates_findall, replace_num_array): ClassFile = open(filename, 'r') filelines = list(ClassFile) # removing header filelines.pop(0) # removing trailer filelines.pop() with open(writefile, 'a') as wf: for i in replace_num_array: for line in filelines: wf.write(line) wf.close() – Paolo Tagliente Jun 12 '20 at 21:43

0 Answers0