-1

i am a beginner in python.

So what I want to do is a script that finds a specific line in multiple files and delete it and rewrite the file with the same name. Something like this but for more files:

similar to problem "Deleting a line in multiple files in python"

i traid quith this code that i can find in the before question but it didn't work

import os

os.chdir('C:\escenarie') source = "*.mgt"

for root, dirs, filenames in os.walk(source):

for f in filenames:
    this_file = open(os.path.join(source, f), "r")
    this_files_data = this_file.readlines()
    this_file.close()
    # rewrite the file with all line except the one you don't want
    this_file = open(os.path.join(source, f), "w")
    for line in this_files_data:
        if line != "          1.200  5                  0.00000"":
            this_file.write(line)
    this_file.close()
  • 4
    Possible duplicate of [using Python for deleting a specific line in a file](https://stackoverflow.com/questions/4710067/using-python-for-deleting-a-specific-line-in-a-file) – Olvin Roght Apr 16 '19 at 14:08
  • 5
    Stack Overflow won't write your code for you. Post what code you have, and what problem you're having with it. – kindall Apr 16 '19 at 14:09
  • 2
    Hi! Welcome to StackOverflow. We are not a code writing service, so please check out the [Help section](https://stackoverflow.com/help/mcve) to learn how to write a question that we can answer. Thanks! – David Culbreth Apr 16 '19 at 14:09
  • Please differentiate: multiple files vs more files. – Austin Apr 16 '19 at 14:09

1 Answers1

0

You ought to learn basic file operations in Python. The code example below should help.

#open file
with open(filename, 'r') as f:
    lines = f.readlines()

#find index of line to remove
for index, line in enumerate(lines):
    if 'delete me' in line:
        #remove line
        lines.pop(index)
        break

#write new file
with open(filename, 'w') as f:
    f.write(''.join(lines))

And to perform this operation on multiple files:

filenames = ['file1.txt', 'file2.txt']
for filename in filenames:
    # ... see code above
joedeandev
  • 626
  • 1
  • 6
  • 15