简体   繁体   English

在Python中使用With的语法无效

[英]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. 以下代码打开一个文件,搜索一个单词或短语,然后在数组中打开该文件,然后在单词或短语之后添加两个新对象,然后将其重新写入文件中,with语句不起作用,当编译后会产生语法错误,指出文件= open(...)'='无效,但它是赋值运算符。 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()

You need to use the as keyword: 您需要使用as关键字:

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

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

Here is a reference on Python's with statement . 这是有关Python的with语句的参考。


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. 使用with语句打开文件将导致在退出with语句的代码块时自动关闭文件。 In fact, that is the only reason why you use a with statement to open files. 实际上,这是您使用with语句打开文件的唯一原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM