python - 尝试使用正则表达式删除行并写入新文件时出错
问题描述
我有一个文本文件,其中每一行都以“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
当我运行这段代码时
import re
pattern = re.compile("^0\s+$")
with open('test.txt', 'w') as file:
with open('test_02.txt') as append_file:
for line in file:
if not pattern(line):
append_file.write(" "+r)
append_file.write("\n")
但是当我运行它时,我收到以下错误消息
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'
我之前使用过相同的“with open”命令从文本中删除停用词并将它们保存到一个新文件中,所以我不确定为什么它现在会产生该错误,而且我没有任何运气故障排除。
解决方案
- 如果您打算写入该文件,则将文件打开为可写:
with open( 'name', 'w') as fout
等等。 - 你不能调用已编译的
re
模式pattern(line)
,你必须使用pattern.match(line)
或类似的东西。 - 创建
re
模式时,使用r'...'
字符串作为模式通常是个好主意。 append_file.write(" "+r)
是一个错误,因为r
没有在任何地方定义。
推荐阅读
- sql-server - 使用文本文件批量插入创建表
- javascript - 在所有异步、嵌套、$.each 数据库调用完成后做一些事情
- c# - 如何从 WPF 中的文本框中获取换行?
- r - 如何在for循环中跳过NA值
- css - 使用 Stylish 调整特定 div 类的填充宽度?
- c++ - OpenCV 2 在 inRange 期间因 stackoverflow 崩溃
- python - Python Plotly Pandas 的可视化问题?
- xml - 亚马逊 MWS Scratchpad 错误 50001 格式错误的 XML
- javascript - ReactJS - 使用 iframe 静默更新令牌
- powershell - 使用 powershell 将 zip 文件发送并提取到 azure VM