【问题标题】:Add/Append text to the end of multiple lines in a specific range in a text file在文本文件的特定范围内的多行末尾添加/追加文本
【发布时间】:2021-04-09 00:22:31
【问题描述】:

我正在尝试使用 python 编程将不同的文本附加到特定范围内的多行末尾到文本文件中。

我的文本文件中的示例数据:

Cat 1: 27
Cat 2: 33
Cat 3: 15
Cat 4: 
Cat 5: 
Cat 6: 
Cat 7: 89

我想将这组数据附加到带有文本“Cat 4”到“Cat 6”的行中:

44
22
64

我希望 python 程序的输出做到这一点:

Cat 1: 27
Cat 2: 33
Cat 3: 15
Cat 4: 44
Cat 5: 22
Cat 6: 64
Cat 7: 89

我在网上找到了这段代码,但它只是用新文本替换文本。它不附加文本,您必须使用单独的文件来实现它:

# create a dict of find keys and replace values
findlines = open('find.txt').read().split('\n')
replacelines = open('replace.txt').read().split('\n')
find_replace = dict(zip(findlines, replacelines))

with open('data.txt') as data:
    with open('new_data.txt', 'w') as new_data:
        for line in data:
            for key in find_replace:
                if key in line:
                    line = line.replace(key, find_replace[key])
            new_data.write(line)

到目前为止,我不知道我需要什么代码,因为我是编程新手。我需要什么 python 代码来实现这一点,我怎样才能让它与一个文件而不是三个文件一起工作?另外,如何让程序一次读取一行,而不是一次将所有数据加载到内存中?我希望能够将这个程序用于大量这样的文本文件,并且我不希望它因为文本文件中的大量数据而冻结我的计算机。感谢您的帮助。

【问题讨论】:

    标签: python file text


    【解决方案1】:

    您应该做的是打开文件进行读写,读取每一行,然后提取 Cat number,将其与您有兴趣替换的进行比较,并将新文本附加到该行。解析完所有行后,将指针设置为文件的开头,然后再次写入,例如:

    import re
    
    numbers = [44, 22, 64]
    start = 4
    end = 6
    
    pattern = re.compile(r'^Cat (\d+):')
    
    with open('file.txt', 'r+') as file:
        updated_lines = []
        for line in file.readlines():
            line = line.strip()
    
            match = pattern.match(line)
            number = int(match.group(1)[0])
    
            if start <= number <= end:
                add_number = numbers[number - start]
                line = line + ' ' +  str(add_number)
    
            updated_lines.append(line + '\n')
    
        file.seek(0)
        file.writelines(updated_lines)
    

    【讨论】:

    • 我试过这个例子,我得到了这个:第 19 行 line = f"{line} {add_number}" ^ SyntaxError: invalid syntax
    • @ubuntuuser771 这意味着fstrings 不适用于您的python 版本。检查编辑。
    • 我在 Ubuntu 20.04.2 上安装了 python2 版本 2.7.18 和 python3 版本 3.8.5。我用 fstrings 尝试了代码并得到以下错误:对于 Python2:第 19 行 line = f"{line} {add_number}" ^ SyntaxError: invalid syntax。对于 Python3:第 15 行,在 number = int(match.group(1)[0]) AttributeError: 'NoneType' object has no attribute 'group'
    • 使用新代码,我得到了这些错误:对于 Python2:第 15 行,在 number = int(match.group(1)[0]) AttributeError: 'NoneType' object has no属性“组”。对于 Python3:第 15 行,在 number = int(match.group(1)[0]) AttributeError: 'NoneType' object has no attribute 'group'
    • 该程序适用于我在上面使用 python3 的问题中提供的示例。前一个带有 fstrings 的函数不适用于 python2。当我将文本文件中的文本从“Cat =”更改为“4-1=”时,python3 出现此错误:第 15 行,在 number = int(match.group(1)[0 ]) AttributeError:“NoneType”对象没有属性“组”。我还想将此程序与具有不同文本的多个不同文本文件一起使用,同时将其他单词、字符、字母、数字等单独附加到每个文件。这可能吗?谢谢。
    猜你喜欢
    • 2022-06-11
    • 2015-05-13
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多