Downdog555
Downdog555

Reputation: 31

Invalid syntax on using With in Python

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()

Upvotes: 0

Views: 87

Answers (1)

user2555451
user2555451

Reputation:

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.

Upvotes: 4

Related Questions