0

the following code opens a file searches for a word or phrase, then opens the file in an array, it then adds two new objects after the word or phrase and then re-writes it to the file, the with statments do not work, when compiled it produces a syntax error saying the file = open(...) the '=' is not valid but it is the assignment operator. help?

def edit(file_name,search_parameters,added_data,second_data):

    with(file = open(file_name,'r')):
        lines = list(file)
        file.close()
    linenum = (num for (num,line) in enumerate(lines) if search_parameters in line).next()
    lines[linenum+1] = added_data
    lines[linenum+1] = second_data

    with (file2 = open(file_name,"w")):
        file2.writelines(line + '\n' for line in lines)
        file2.close()
1
  • In python, assignment is a statement, not an operator. It does not return a value. Commented Mar 14, 2014 at 22:50

1 Answer 1

4

You need to use the as keyword:

with open(file_name,'r') as file:

with open(file_name,"w") as file2:

Here is a reference on Python's with statement.


Also, these two lines are unncessary:

file.close()

file2.close()

Using a with statement to open a file will cause it to be closed automatically when the with statement's code block is exited. In fact, that is the only reason why you use a with statement to open files.

Sign up to request clarification or add additional context in comments.

2 Comments

It is also noteworthy that OP does not need to explicitly close the file. Perhaps an explanation of the with statement is required.
@AlexThornton - Good idea, I missed that. Let me mention it.

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.