Dan Dan - 23 days ago 10
Python Question

shutil.copyfile does not copy all lines

77 lines are missing from my temporary output file

cloneTemp.txt
, when using
shutil.copyfile()
.
Why is this?

This file contains two functions. The first function creates a temporary file which will contain the data generated from a file called
newFileLocation
created by my
Main.py


import os
import sys
import shutil


def cloneTemp(newFileLocation):
cloneFile = open('cloneTemp.txt', 'w+')
shutil.copyfile(newFileLocation, 'cloneTemp.txt')


This second function will then send new lines to the beginning of
cloneTemp.txt
, copy the data from the newFileLocation to cloneTemp.txt and finally, write at the end of the cloneTemp.txt:


def gridEnable(newFileLocation):

if(x < 200):
print x
cloneTemp.write(x)
else:
cloneTemp.write(y)

shutil.copyfile('cloneTemp.txt', newFileLocation)


Yet, lines are missing when it's copied over. Why is
newFileLocation
not being copied in it's entirety?

EDIT

newFileLocation
is a file containing the output from
Main.py
, that is all. Since I can't prepend to the beginning of the
newFileLocation
, I am creating a temporary file of
newFileLocation
called
cloneTemp.txt
to copy over the data only after I've added the lines into the empty
cloneTemp.txt
that I require. After the lines are added,
shutil.copyfile()
should copy
newFileLocation
in it's entirety to
cloneTemp.txt
. Yet, it is not.

Answer

I'm still confused about what you want but here is a strawman answer. This code will take a file in newFileLocation and will add data to the front and back of the file.

with open('cloneTemp.txt', 'w') as tmp:
    tmp.write(x)
    with open(newFileLocation) as newfile:
        shutil.copyfileobj(newfile, tmp)
    tmp.write(y)
os.rename('cloneTemp.txt', newFileLocation)

So, lets test

import shutil
import os

# file to test
newFileLocation = 'testfile.txt'
open(newFileLocation, 'w').write('this\nis\na\ntest\n')
print('before:')
print(open(newFileLocation).read())

with open('cloneTemp.txt', 'w') as tmp:
    tmp.write('header\n')
    with open(newFileLocation) as newfile:
        shutil.copyfileobj(newfile, tmp)
    tmp.write('footer\n')
os.rename('cloneTemp.txt', newFileLocation)
print('after:')
print(open(newFileLocation).read())

Produces

before:
this
is
a
test

after:
header
this
is
a
test
footer
Comments