2024-06-26 14:18:33 发布
网友
我想先创建一个文件的副本,然后检查文件的大小,如果大小小于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来简化获取文件大小和添加所需的填充。你知道吗
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)
你可以这样做:
它使用新python的
pathlib
来简化获取文件大小和添加所需的填充。你知道吗相关问题 更多 >
编程相关推荐