首页 > 解决方案 > 如何修改文件以使每行的字符数相同?

问题描述

我有一个包含多行数据的文本文件。在将其传递到下游之前,我需要每行具有相同数量的字符。

我有一个 python 脚本,可以找到文件中最长的行,并尝试使用 ljust 函数使每一行都达到该长度。

    args=parse_args()
    readfile = args.inputfile

    #find the longest line in the file, and set that as longest
    longest = 0
    #open the file up
    with open(str(args.inputfile).strip('[]').strip("''")) as readfile:
        #find the longest line in the file and make note of how long.
        for line in readfile:
            if len(line) > longest:
                longest = len(line)
            else:
                pass
        print("The longest line is " + str(longest) + " characters long. ")
        #make each line exactly that long
        for line in readfile:
            readfile.write(line.ljust(longest)) #make it longest long and fill with spaces.

        readfile.close()

问题是文件没有发生任何事情。该脚本输出最长的行是 31 个字符长,但没有像我期望的那样在较短的行的末尾添加空格。

标签: pythonfile-writing

解决方案


您用尽了文件迭代器;当您尝试写入时,文件中没有任何内容可供访问。如果你费心去追踪执行,你就会看到这一点。请参阅这个可爱的调试博客寻求帮助。

特别是,让我们看看您的循环。

#open the file up
with open(str(args.inputfile).strip('[]').strip("''")) as readfile:
    #find the longest line in the file and make note of how long.
    for line in readfile:

for语句通过file对象定义的迭代器起作用;您可以将其视为一次性使用主题公园的文件,在您点击with open声明时设置。

        if len(line) > longest:
            longest = len(line)

我删除else: pass了,因为它没有做任何事情。

在这里,离开for循环时,文件描述符的“书签”位于文件末尾。

    print("The longest line is " + str(longest) + " characters long. ")
    #make each line exactly that long

    for line in readfile:

您不会输入此代码;书签已经在代码的末尾。没有其他东西可以读了。您得到 EOF 响应并完全跳过循环。

        readfile.write(line.ljust(longest)) #make it longest long and fill with spaces.

    readfile.close()

修复相当简单:仅使用第一个块来确定最大行长度。完全退出该with块。然后专门为写作制作一个新的。请注意,您需要一个新的输出文件,或者您需要保留第一次读取的输入。您的目的是覆盖原始文件,这意味着您不能同时读取它。

如果这仍然令人困惑,那么请阅读一些关于文件处理的教程。


推荐阅读