Jakov.M
Jakov.M

Reputation: 31

How to change a specific word in a specific line in a text file

My text file looks like this:

Fjodor Dostojevski|Zlocin i kazna|1866|9788897572657|roman|4500|50|true|   
Dragoslav Mihajlovic|Kad su cvetale tikve|1968|3332221115554|drama|3000|20|true|   
Viliam Sekspir|Hamlet|1600|3214569879878|drama|6500|60|true|

I need to search for the the number like 9788897572657 or 3332221115554, and if the number is in line, then change word true to false in that line.

Upvotes: 2

Views: 80

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49842

Here is some code which will process your lines. For each line in the data, it will:

  1. split the line on the |
  2. check if the field in question is in the sample set
  3. if present, insert false.
  4. put the line back together with a join
  5. add it to the output list

Code:

# build a set of the keys we will look for
looking_for = {"9788897572657", "3332221115554"}

output_data = []
for line in test_data:
    fields = line.split('|')
    if fields[3] in looking_for:
        fields[7] = 'false'
    output_data.append('|'.join(fields))

for line in output_data:
    print(line)

Test Data:

test_data = [x.strip() for x in """
    Fjodor Dostojevski|Zlocin i kazna|1866|9788897572657|roman|4500|50|true|
    Dragoslav Mihajlovic|Kad su cvetale tikve|1968|3332221115554|drama|3000|20|true|
    Viliam Sekspir|Hamlet|1600|3214569879878|drama|6500|60|true|
""".split('\n')[1:-1]]

Produces:

Fjodor Dostojevski|Zlocin i kazna|1866|9788897572657|roman|4500|50|false|
Dragoslav Mihajlovic|Kad su cvetale tikve|1968|3332221115554|drama|3000|20|false|
Viliam Sekspir|Hamlet|1600|3214569879878|drama|6500|60|true|

Upvotes: 1

Related Questions