Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试使用正则表达式删除行并写入新文件时出错_Python_Regex - Fatal编程技术网

Python 尝试使用正则表达式删除行并写入新文件时出错

Python 尝试使用正则表达式删除行并写入新文件时出错,python,regex,Python,Regex,我有一个文本文件,其中每一行都以“0”开头,后跟一个制表符,然后理想情况下是一些文本-然而,有些行只有一个“0”后跟空白,我需要删除它们 编辑:我向第二个文件路径添加了“w”,如下所示,但现在我收到以下错误消息: --------------------------------------------------------------------------- TypeError Traceback (most recent ca

我有一个文本文件,其中每一行都以“0”开头,后跟一个制表符,然后理想情况下是一些文本-然而,有些行只有一个“0”后跟空白,我需要删除它们

编辑:我向第二个文件路径添加了“w”,如下所示,但现在我收到以下错误消息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ed7474583899> in <module>
      3     with open('test_02.txt', 'w', ) as append_file:
      4         for line in file:
----> 5             if not pattern(line):
      6                 append_file.write(" "+r)
      7         append_file.write("\n")

TypeError: 're.Pattern' object is not callable
但是当我运行它时,我得到以下错误消息

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-26-41d28ce0cbdf> in <module>
      3 pattern = re.compile("^0\s+$")
      4 with open('test.txt') as file:
----> 5     with open('test_02.txt') as append_file:
      6         for line in file:
      7             if not pattern(line):

FileNotFoundError: [Errno 2] No such file or directory: 'test_02.txt'
FileNotFoundError回溯(最近一次调用)
在里面
3模式=重新编译(^0\s+$)
4打开('test.txt')作为文件:
---->5打开('test_02.txt')作为附加文件:
6对于文件中的行:
7如果不是图案(线条):
FileNotFoundError:[Errno 2]没有这样的文件或目录:“test_02.txt”
我以前使用过相同的“with open”命令从文本中删除停止词并将其保存到新文件中,因此我不确定它现在为什么会生成该错误,而且我还没有遇到任何故障排除的机会

  • 如果您计划写入该文件,请以可写方式打开该文件:
    ,并将open('name','w')作为fout
  • 您不能调用编译的
    re
    pattern
    pattern(line)
    ,您必须使用
    pattern.match(line)
    或类似的东西
  • 创建
    re
    模式时,通常最好使用
    r'…'
    字符串作为模式
  • append\u file.write(“+r)
    是一个错误,因为
    r
    没有在任何地方定义

  • 您应该以写入模式
    打开新文件,并将open('test_02.txt',w')作为append_file:
    忽略mode参数时,默认为reading,当然,如果文件不存在,则会失败。
    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-26-41d28ce0cbdf> in <module>
          3 pattern = re.compile("^0\s+$")
          4 with open('test.txt') as file:
    ----> 5     with open('test_02.txt') as append_file:
          6         for line in file:
          7             if not pattern(line):
    
    FileNotFoundError: [Errno 2] No such file or directory: 'test_02.txt'