【问题标题】:Writing nested list to file per line: UnsupportedOperation: not writable每行将嵌套列表写入文件:UnsupportedOperation:不可写
【发布时间】:2022-08-03 21:13:00
【问题描述】:

我试图编写一个代码,从文件中删除以小于 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: not writable ,我不明白为什么。

    标签: python function file


    【解决方案1】:

    玩具代码中的问题似乎是您打开文件进行阅读 用这一行with open(Out,'r') as Out: 然后尝试写入文件,所以我将r 更改为w

    这应该可以解决问题:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 2020-01-03
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多