如何通过在python末尾添加空格来编辑文件以增加大小

我想先创建一个文件副本,然后检查文件的大小,如果大小小于1 MB,则在文件末尾添加空格以使其大小为1 MB。

我已经复制了using下面的代码,但是在文件末尾添加空格时我得到了任何帮助。

from shutil import copyfile
copyfile(self.actualfile,self.copyfile)
QQ5211982511 回答:如何通过在python末尾添加空格来编辑文件以增加大小

您可以这样做:

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)) 
本文链接:https://www.f2er.com/3157083.html

大家都在问