I want to first create a copy of a file and then check the size of the file and if the size is less than 1 MB then add white spaces at end of the file to make it 1 MB size.
I have copied the using below code but I am getting any help for adding white spaces at end of the file.
from shutil import copyfile
copyfile(self.actualfile,self.copyfile)
you can do it like this:
import os
filename = 'file.txt'
size = os.stat(filename).st_size
f = open(filename, "a+")
f.write(" " * (1024*1024 - size))
f.close();
This uses pathlib
from newer Pythons to simplify getting the file's size and adding exactly the padding you want.
#!/usr/bin/env python
import pathlib
import shutil
destfile = pathlib.Path("/tmp/foo")
shutil.copyfile(__file__, destfile)
required_padding = 1024 * 1024 - destfile.stat().st_size
if required_padding > 0:
with destfile.open("ab") as outfile:
outfile.write(b" " * required_padding)
with open(self.actualfile, 'r') as fin: with open(self.copyfile, 'w') as fout: print('{:<1048756}'.format(fin.read()), file=fout)
You can try this:
actual_size = os.path.getsize(self.copyfile)
x = " " * (int(size)-actual_size)
with open(self.copyfile, "a", encoding="utf-8") as f:
f.write(x)
print("Size (In bytes) of '%s':" %os.path.getsize(self.copyfile))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.