Reputation: 55
So I am new to Python and I am trying to create a script that reads 10 lines of data from one text file and then repeats that data 1000 times and writes it to another text file. Reading the file is not the problem, but this is what I have:
fr = open('TR.txt', 'r')
text = fr.read()
print(text)
fr.close()
Now I understand that this opens the file and prints the contents. I just need to take those entries and repeat them 1000 times and then write those to a file. This is what I have so far to write to a file (I know this probably doesn't make sense):
fw = open('TrentsRecords.txt', 'w')
fw.write(text.repeat(text, 1000000))
fw.close()
Upvotes: 1
Views: 1813
Reputation: 180481
from itertools import repeat,islice
fw.write("".join(repeat(text, 10000)))
So:
with open('TR.txt') as fr, open('TrentsRecords.txt', 'w') as fw:
text = list(islice(fr, None, 10)) # get first ten lines
fw.writelines(repeat(line.strip()+"\n", 10000)) # write first ten lines 10000 times
with
will automatically close your files.
Upvotes: 1
Reputation: 16711
Just multiply. If it is a string, it will concatenate. If it is a number, it will multiply.
fw.write(text * 1000000) # add newlines if you want
Look at the Python Documentation. This is taken straight from it.
Strings can be concatenated (glued together) with the
+
operator, and repeated with*
:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
Upvotes: 1