Python 函数错误-未定义文件名
我每隔一周编一个脚本,从文件中找出3位数记录的行。经常这样做,我想我为什么不做一个可以导入的函数呢。我写了这个,然后去测试它。但是,当我运行脚本并执行Python 函数错误-未定义文件名,python,python-3.x,Python,Python 3.x,我每隔一周编一个脚本,从文件中找出3位数记录的行。经常这样做,我想我为什么不做一个可以导入的函数呢。我写了这个,然后去测试它。但是,当我运行脚本并执行 def_recs(文件名,输出) 我明白了 “名称错误:未定义名称‘filename’” 其中“filename”是我要传递的文件名 这是我的密码: import os import re def get_recs(infile, outfile): path = r'<path to my infile file>'
def_recs(文件名,输出)
我明白了
“名称错误:未定义名称‘filename’”
其中“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)
并将一行中有三位数字的所有记录写入一个名为“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)
导入操作系统
进口稀土
路径=r''
将open(os.path.join(path,'newfile'),'r')作为内嵌1:
将open(os.path.join(path,'out'),'w')作为outfile1:
对于填充1中的线:
如果重新匹配(r'(.*)\d\d(.*),第行):
出口1.写线(线)
它运行得很好
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)
导入操作系统
进口稀土
def获取记录(填充、输出文件):
如果类型(填充)!=str:
infle=str(infle)
如果类型(输出文件)!=str:
outfile=str(outfile)
路径=r''
使用open(os.path.join(path,infle),'r')作为infle1:
将open(os.path.join(path,outfile),'w')作为outfile1:
对于填充1中的线:
如果重新匹配(r'(.*)\d\d(.*),第行):
出口1.写线(线)
仍在获取名称错误。我现在正在联机搜索传递字符串参数的正确方法。如果出现名称错误,则表明您没有引用字符串。从编辑中可以看出:
namererror
在函数运行之前被引发。不要调用get\u recs(filename,outfile)
使用get\u recs('filename','outfile')
。粘贴完整的stacktrace(如果需要,可以使用密文)会有所帮助。该函数(因此该行)从未运行过。名称错误是在它出现之前抛出的。出于记录,您可能需要使用isinstance
而不是使用类型相等。如果您忽略了函数一点,并且在新文件中尝试不使用任何其他内容的print(filename)
,您也会得到namererror
。它与函数定义无关。当您尝试调用任何函数时,python必须首先收集要传递给它的参数。当您传入filename
时,它试图查找该名称所引用的内容,但失败。当您传入'filename'
时,它是一个文本字符串,因此不涉及任何查找,字符串将被传递。你也可以先做filename='filename'
,然后再做print(filename)
,这样就行了。没问题,我们都是从某个地方开始的。很高兴它开始有意义了——你的解释听起来很贴切。
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)