如何使用Python查找一行中的字符串并更改字符串后n行的文本

2024-09-19 23:27:49 发布

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

我需要在文本文件中找到“translate”的每个实例,并在找到文本后替换值4行:

"(many lines)
                }
            }   
        translateX xtran        
            {   
            keys    
                {
                k  0  0.5678
                }
            }   
(many lines)"

值0.5678需要为0。它总是在"translate"字符串下面4行 该文件最多有10000行。 示例文本文件名:01F.pz2。在

我还想在文件夹中循环,并对每个扩展名为pz2(最多40个)的文件重复这个过程。在

任何帮助都将不胜感激!在

谢谢。在


Tags: 文件实例字符串文本文件夹示例过程keys
2条回答

我不太确定替换文件中0.5678的逻辑,因此我使用了一个函数-将其更改为您需要的任何内容,或者更详细地解释您想要的内容。最后一个号码?只有浮点数?在

尝试:

import os    

dirname = "14432826"
lines_distance= 4

def replace_whatever(line):
    # Put your logic for replacing here
    return line.replace("0.5678", "0")

for filename in filter(lambda x:x.endswith(".pz2") and not x.startswith("m_"), os.listdir(dirname)):
    print filename
    with open(os.path.join(dirname, filename), "r") as f_in, open(os.path.join(dirname,"m_%s" % filename), "w") as f_out:
        replace_tasks = []
        for line in f_in:
            # search marker in line
            if line.strip().startswith("translate"):
                print "Found marker in", line,
                replace_tasks.append(lines_distance)                
            # replace if necessary
            if len(replace_tasks)>0 and replace_tasks[0] == 0:
                del replace_tasks[0]
                print "line to change is", line,
                line_to_write = replace_whatever(line)
            else:
                line_to_write = line
            # Write to output
            f_out.write(line_to_write)
            # decrease counters
            for i, task in enumerate(replace_tasks):
                replace_tasks[i] -= 1

代码中的注释应该有助于理解。主要概念是列表replace_tasks,它记录下一行要修改的时间。在

备注:代码示例表明文件中的数据是结构化的。阅读此结构并对其进行操作,而不是在纯文本文件上搜索和替换方法,这无疑是一种节省。在

Thorsten,我重新命名了我的原始文件,扩展名为.old,下面的代码可以工作:

import os
target_dir = "."


# cycle through files
for path, dirs, files in os.walk(target_dir):
    # file is the file counter
    for file in files:
        # get the filename and extension
        filename, ext = os.path.splitext(file)
        # see if the file is a pz2
        if ext.endswith('.old') :
            # rename the file to "old"
            oldfilename = filename + ".old"
            newfilename = filename + ".pz2"
            old_filepath = os.path.join(path, oldfilename)
            new_filepath = os.path.join(path, newfilename)
            # open the old file for reading
            oldpz2 = open (old_filepath,"r")
            # open the new file for writing
            newpz2 = open (new_filepath,"w")
            # reset changeline
            changeline = 0
            currentline = 0
            # cycle through old lines
            for line in oldpz2 :
                currentline = currentline + 1
                if line.strip().startswith("translate"):
                        changeline = currentline + 4
                if currentline == changeline :
                    print >>newpz2,"                k  0  0"
                else :
                    print >>newpz2,line

相关问题 更多 >