我试图编写一个代码,从一个以小于T的数字开头的文件中删除任何一行,然后将剩余的行写入另一个文件。
def filter(In,Out, T):
with open(In,'r') as In:
with open(Out,'r') as Out:
lines=In.readlines()
lines=[[e for e in line.split()] for line in lines]
lines=[line for line in lines if int(line[0])>=T]
for line in lines:
for word in line:
Out.write(f"{word} ")
return None
我以为代码可能会把单词写在一长行中,而不是每行一行,但它只是返回了UnsupportedOperation:不可写,我不明白为什么。
您的代码似乎有一些错误
-
您用
with open(Out,'r') as Out:
行打开文件进行读取,然后尝试写入该文件,因此我将r
更改为w
-
你试图在文件已经打开进行读取时打开它进行写入(你不能在文件打开时打开它(,所以我在你完成读取后将写入的代码移回文件
-
您打开文件进行读取,并将其命名为
In
,但这个名称已经是您正在获取的参数的名称
这应该做的技巧:
def filter(In_name,Out, T):
with open(In_name,'r') as In:
lines=In.readlines()
lines=[[e for e in line.split()] for line in lines]
lines=[line for line in lines if int(line[0])>=T]
with open(Out, 'w') as Out:
for line in lines:
for word in line:
Out.write(f"{word} ")
return None