Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...