0

I am trying to do what for many will be a very straight forward thing but for me is just infuriatingly difficult. I am trying search for a line in a file that contains certain words or phrases and modify that line...that's it. I have been through the forum and suggested similar questions and have found many hints but none do just quite what I want or are beyond my current ability to grasp.

This is the test file:

# 1st_word  2nd_word

# 3rd_word  4th_word

And this is my script so far:

############################################################
file = 'C:\lpthw\\text'
f1 = open(file, "r+")
f2 = open(file, "r+")
############################################################

def wrline():
    lines = f1.readlines()
    for line in lines:
        if "1st_word" in line and "2nd_word" in line:
            #f2.write(line.replace('#\t', '\t'))
            f2.write((line.replace('#\t', '\t')).rstrip())
    f1.seek(0)

wrline()

My problem is that the below inserts a \n after the line every time and adds a blank line to the file.

f2.write(line.replace('#\t', '\t'))

The file becomes:

    1st_word    2nd_word


#   3rd_word    4th_word

An extra blank line between the lines of text.

If I use the following:

f2.write((line.replace('#\t', '\t')).rstrip())

I get this:

    1st_word    2nd_wordd

#   3rd_word    4th_word

No new blank line inserted but and extra "d" at the end instead.

What am I doing wrong?

Thanks

3 Answers 3

1

Your blank line is coming from the original blank line in the file. Writing a line with nothing in it writes a newline to the file. Instead of not putting anything into the written line, you have to completely skip the iteration, so it does not write that newline. Here's what I suggest:

def wrline():
    lines = open('file.txt', 'r').readlines()
    f2 = open('file.txt', 'w')
    for line in lines:
        if '1st_word' in line and '2nd_word' in line:
            f2.write((line.replace('# ', ' ')).rstrip('\n'))
        else:
            if line != '\n':
                f2.write(line)
    f2.close()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the comment. But tried as you suggested and out put was this: 1st_word 2nd_word# 3rd_word 4th_word_word
Then remove the .rstrip(), so that there is a newline between then
1

I would keep read and write operations separate.

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

#parse, change and write back
with open(file, 'w') as f:
    for line in lines:
        if line.startswith('#\t'):
            line = line[1:]
    f.write(line)

Comments

0

You have not closed the files and there is no need for the \t

Also get rid of the rstrip()

Read in the file, replace the data and write it back.. open and close each time.

fn = 'example.txt'
new_data = []

# Read in the file
with open(fn, 'r+') as file:
    filedata = file.readlines()

# Replace the target string
for line in filedata:
    if "1st_word" in line and "2nd_word" in line:
        line = line.replace('#', '')
    new_data.append(line)

# Write the file out again
with open(fn, 'w+') as file:
    for line in new_data:
        file.write(line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.