python - 函数错误 - 未定义文件名
问题描述
我每隔一周启动一个脚本来抓取具有 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。我现在正在网上搜索传递字符串参数的正确方法。
解决方案
推荐阅读
- java - android Studio 的 DownloadManger 类中“外部”的确切参考是什么?
- javascript - ASP / HTML / Javascript 无法正常工作
- mongodb - MongoDB 使用匹配而不是聚合
- react-native - 在视图中找不到意外的令牌反应本机
- css - CSS网格不考虑minmax中的最小值以及自动调整
- c++ - 有没有办法可以将字符串写入文件?
- c# - 手动杀死线程,之前创建
- python - Tensorflow 2.0:如何在使用 tf.saved_model 时更改输出签名
- node.js - 无法在 Electron 应用程序的 NPM 依赖项中使用加密
- django - 在呈现响应之前删除消息