Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

python 3.x - I am trying to edit a line in a file, this line appears in multiple areas but I only want to edit some of them

So I have been looking at other examples of this and have come up with the following:

def editPicReplace():
    for somefile in os.listdir(source_folder):
        with open(os.path.join(source_folder, somefile), "r") as file:
             filedata = file.readlines()


             index_list = []
        for index, line in enumerate(filedata):
            if line.startswith('            picture "TR_NAME_XF"'):
                index_list.append(index)
                print(index_list)

        for a in index_list:

            for i, line in enumerate(filedata):
                if i == a + 7:
                    filedata[i]= line[:18].replace('2', '') + line[18:]
                    print(line)

        with open(os.path.join(source_folder, somefile), "w") as file:
                    filedata = "".join(filedata)
                    file.write(filedata)        

at the print(line)statement it prints out the correct edit to the required lines but the problem I'm having is the new edit does not get written to the file.

I have mucked around with fileinputand with tempfilebut still had no luck with writing the new edit back to the file.

Any help with this would be great, thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...