是什么导致我的代码膨胀文本文件的大小?

2024-05-04 08:50:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个Python程序来遍历目录中的文本文件,并用添加的行号创建每个文件的新版本。以下是程序中的相关功能:

def create_lined_ver(filename):
    new_text = []

    with open(filename + ".txt", "r+") as f:
        text = f.readlines()
        for (num, line) in enumerate(text):
            new_text.append("[{0}]: ".format(num) + line)

    with open(filename + "_lined" + ".txt", "a+") as f:
        for line in new_text:
            f.write(line)

为了测试它,我在一批文本文件上运行它,然后出于好奇,再次运行它(在已经编号的文件中添加第二组行号)。我注意到,每次运行程序时,新创建的文件的文件大小都比每行添加5-6个字符时的大小要大得多。文件大小从150KB(原始)跳到7001800,然后每次运行3000kB。你知道吗

是什么导致文件大小增加这么多?你知道吗


Tags: 文件text程序txtnewforaswith
3条回答

在第9行,打开带有“a+”标志的文件。这使文件可用于附加和读取。有关open命令的不同模式的描述,请参见here。通过以“w”模式打开文件,您将覆盖现有文件。你知道吗

我不认为你需要使用列表或附加到文件。你知道吗

你在找这样的东西。你知道吗

def create_lined_ver(filename):
    with open(filename + ".txt") as f_in, open(filename + " _lined.txt", "w") as f_out:
        for num, line in enumerate(f_in):
            f_out.write("[{}]: {}\n".format(num,  line))

如前所述,在注释中,每次运行代码时都会附加到行版本。相反,请尝试:

def create_lined_ver(filename):

    with open(filename + ".txt", "r") as f:
        text = f.readlines()

    new_text = ["[{0}]: ".format(num) + line for (num, line) in enumerate(text)]

    with open(filename + "_lined" + ".txt", "w") as f:
        f.write(''.join([new_text]))

相关问题 更多 >