为什么 函数参数变量没定义
本帖最后由 Twilight6 于 2020-3-31 09:46 编辑def judge(file1_,file2_):
file1 = open(file1_+'.txt',encoding = 'utf-8')
file2 = open(file2_+'.txt',encoding = 'utf-8')
count = 0 ; times = 0 ; false = [] #count 记录错误行数 、times 记录错误次数
judge_file_different()
def judge_file_different(): # 判断文件不同处
for each_line_file1 in file1:
count +=1
each_line_file2 = file2.readline()
if each_line_file1 != each_line_file2 :
false.append(count) # 将错误的行数整理成列表
times += 1
file1.close()
file2.close()
if times != 0:
print('两个文本文件有【%d】处不同:'%times)
for i in false:
print('第 %d 行不同'%int(i))
else:
print('两文本完全相同')
错误代码:
judge('file1','file2')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:/Users/86151/Desktop/help.py", line 6, in judge
judge_file_different()
File "C:/Users/86151/Desktop/help.py", line 8, in judge_file_different
for each_line_file1 in file1:
NameError: name 'file1' is not defined
为什么这样调用会说file1,file2没定义?
是局部变量和全局变量的原因吗?
'file1','file2' 不应该是文件路径吗?
ba21 发表于 2020-3-30 23:17
'file1','file2' 不应该是文件路径吗?
是我file1.txtfile2.txt 就是文件名 Twilight6 发表于 2020-3-30 23:20
是我file1.txtfile2.txt 就是文件名
judge('file1','file2')
难道是我眼睛有问题了???怎么没看见.txt ba21 发表于 2020-3-30 23:44
judge('file1','file2')
难道是我眼睛有问题了???怎么没看见.txt
def judge(file1_,file2_):
file1 = open(file1_+'.txt',encoding = 'utf-8')
file2 = open(file2_+'.txt',encoding = 'utf-8')
emmm 这真是神一样的代码。。
不想缩进
就把 judge_file_different(file1, file2) 传参进去
def judge(file1_,file2_):
file1 = open(file1_+'.txt',encoding = 'utf-8')
file2 = open(file2_+'.txt',encoding = 'utf-8')
count = 0 ; times = 0 ; false = [] #count 记录错误行数 、times 记录错误次数
judge_file_different()
def judge_file_different(): # 判断文件不同处
for each_line_file1 in file1:
count +=1
each_line_file2 = file2.readline()
if each_line_file1 != each_line_file2 :
false.append(count) # 将错误的行数整理成列表
times += 1
file1.close()
file2.close()
if times != 0:
print('两个文本文件有【%d】处不同:'%times)
for i in false:
print('第 %d 行不同'%int(i))
else:
print('两文本完全相同')
ba21 发表于 2020-3-31 00:07
这真是神一样的代码。。
不想缩进
不行的 ba21 发表于 2020-3-31 00:07
这真是神一样的代码。。
不想缩进
我自己解决了,不用第二个函数删了就OK了
for each_line_file1 in file1 的file1被屏蔽了所以报错了 啾啾 给自己最佳??!
页:
[1]