[英]How increase an image to a specific size by adding white transparent pixels in python (preferably using opencv)
[英]How to edit a file to increase the size by adding white spaces at end in python
我想首先创建一个文件的副本,然后检查文件的大小,如果大小小于 1 MB,则在文件末尾添加空格以使其大小为 1 MB。
我已经复制了使用下面的代码,但我得到了在文件末尾添加空格的任何帮助。
from shutil import copyfile
copyfile(self.actualfile,self.copyfile)
你可以这样做:
import os
filename = 'file.txt'
size = os.stat(filename).st_size
f = open(filename, "a+")
f.write(" " * (1024*1024 - size))
f.close();
这使用来自较新 Python 的pathlib
来简化获取文件大小并准确添加所需的填充。
#!/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)
你可以试试这个:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.