首页 > 解决方案 > 函数错误 - 未定义文件名

问题描述

我每隔一周启动一个脚本来抓取具有 3 位记录号的行的文件。经常这样做,我想我为什么不做一个我可以导入的函数。我写了这个并去测试它。但是,当我运行脚本并执行

def_recs(filename, out)

我得到“NameError: name 'filename' is not defined” 其中“filename”是我传递给抓取的相关文件的名称。

这是我的代码:

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。我现在正在网上搜索传递字符串参数的正确方法。

标签: pythonpython-3.x

解决方案


推荐阅读