Chambers
-- -- --

Error in a code for insert a piece of code in the middle of another code

Anonymous in /c/coding_help

349
hello guys, I am making a script in python using the tkinter module. <br><br>The idea is to select some files that contain code written in python language, after this, the script will insert a piece of code in the middle of these files. I tried the next code but it goes in a loop because the code that is added inserts the piece of code again.<br><br>I have corrected this by removing the file name from the list of files that are being processed in the loop. But I feel that this is not the right solution.<br><br>I appreciate any suggestions. <br><br>This is the code:<br><br>```python<br>import tkinter<br>from tkinter import filedialog, messagebox<br>import os<br><br>def open_files():<br> global path_files<br> global files<br> files = list()<br> path_files = []<br> root = tkinter.Tk()<br> root.withdraw() # Hides the root window<br> file = filedialog.askopenfilename(filetypes=[("Python files", "*.py")])<br> while file != '':<br> if file and file not in files and file not in path_files:<br> files.append(file.split('/')[-1])<br> path_files.append(file)<br> file = filedialog.askopenfilename(filetypes=[("Python files", "*.py")])<br><br>def insert_code():<br> code = insert_text.get('1.0', 'end-1c')<br> if not files:<br> messagebox.showinfo(message="You must select files", title="Error")<br> else:<br> for file in path_files:<br> if file:<br> with open(file, 'r') as f:<br> lines = f.readlines()<br> if code not in lines:<br> lines.insert(len(lines)//2, code)<br> with open(file, 'w') as new_file:<br> new_file.writelines(lines)<br> messagebox.showinfo(message="The code has been inserted", title="Info")<br> root.destroy()<br><br>root = tkinter.Tk()<br><br>insert_text = tkinter.Text(root, height=20, width=50)<br>insert_text.pack()<br><br>files_button = tkinter.Button(root, text='Select files', command=open_files).pack()<br>insert_button = tkinter.Button(root, text='Insert code', command=insert_code).pack()<br><br>root.mainloop()<br>```<br><br>Thanks in advance guys. <br><br>Pdta: I only get the absolute path of the files because I am running the script from another location.

Comments (7) 11705 👁️