user11803465
user11803465

Reputation:

How to write the same data over and over on a file?

I want to make a script that will allow me to write N times the same paragraph of data but I have no idea how to do it, can you help me?

i tried this :

fin = open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\1212.osg", "rt")
fout = open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\testreecrtiure.osg", "wt")

for line in fin:
             fout.write(line.write("...."))

but i dont know if i have to use a loop or something like this

Upvotes: 0

Views: 37

Answers (2)

tripleee
tripleee

Reputation: 189507

Here's a simple implementation which writes the input file 42 times.

with open('output', 'w') as fout:
    for x in range(42):
        with open('input', 'r') as fin:
            for line in fin:
                fout.write(line)

Instead of repeatedly closing and reopening the input file, you can rewind it with seek() if you wish; but I prefer this approach, which also takes care of automatically closing both files at the end, which you forgot to do in your code.

(You should probably avoid hard-coding absolute paths in your code.)

Upvotes: 1

user12013935
user12013935

Reputation: 15

Try this:

fin = open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\1212.osg", "r")
fout = open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\testreecrtiure.osg", "w")


for line in fin:
    fout.write(line)

fin.seek(0,0)

for line in fin:
    fout.write(line)

Once you finish "read and write", the pointer of "fin" should be moved to the beginning.

So you need to add this line:fin.seek(0,0) before you start another "read and write".

Here is the code of write N times

fin = open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\1212.osg", "r")
fout = open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\testreecrtiure.osg", "w")

N=5  # For example, repeat 5 times
for count in range(0,N):
    for line in fin:
        fout.write(line)
    fin.seek(0,0)

Upvotes: 0

Related Questions