我每两周启动一个脚本,以刮擦3位记录数字的行的文件。我经常这样做,我想为什么不做一个可以导入的函数。我写了这个然后去测试。但是,当我运行脚本并执行
def_recs(filename, out)
我明白了 “ NameError:名称'文件名'未定义” 其中“文件名”是我要抓取的有问题文件的名称。
这是我的代码:
import os
import re
def get_recs(infile, outfile):
path = r'<path to my infile file>'
with open(os.path.join(path, infile),'r') as infile1:
with open(os.path.join(path, outfile),'w') as outfile1:
for line in infile1:
if re.match(r'(.*)\d\d\d(.*)',line):
outfile1.writelines(line)
将其保存在名为“ ToolBelt.py”的文件中。我的最终目标是能够执行以下操作:
from ToolBelt import get_recs
get_rec(newfile, out)
,并将所有连续三位数的记录写入名为“ out”或我作为第二个参数传递的文件的文件。
编辑:仅需添加,当我将上述代码修改为不起作用时:
import os
import re
path = r'<path to my infile file>'
with open(os.path.join(path, 'newfile'),'r') as infile1:
with open(os.path.join(path, 'out'),'w') as outfile1:
for line in infile1:
if re.match(r'(.*)\d\d\d(.*)',line):
outfile1.writelines(line)
运行正常。
Edit2:刚刚尝试将其更改为
import os
import re
def get_recs(infile, outfile):
if type(infile) != str:
infile = str(infile)
if type(outfile) != str:
outfile = str(outfile)
path = r'<path to my infile file>'
with open(os.path.join(path, infile),'r') as infile1:
with open(os.path.join(path, outfile),'w') as outfile1:
for line in infile1:
if re.match(r'(.*)\d\d\d(.*)',line):
outfile1.writelines(line)
仍然收到NameError。我现在正在网上搜索传递字符串参数的正确方法。