Python 结果显示的东西与我预期的不同

  • 本文关键字:结果 显示 Python python
  • 更新时间 :
  • 英文 :


我已经编写了这段代码,但结果返回no such file exists,即使所有文件都存在。

def shomaresh_tedad_kalamat(esme_file):
try:
with open(esme_file) as f:
mohtaviat=f.read()
except:
print("no such a file exists") 
pass
else:
kalamat=mohtaviat.split()
tedad_kalamat=len(kalamat)
print(esme_file , tedad_kalamat ," kalame darad")  
esme_file=['data1.txt','data2w.txt','data3w.txt','a.txt']
for esm in  esme_file:   
shomaresh_tedad_kalamat(esme_file)

你能帮我解决这个问题吗?

试试这个:

def shomaresh_tedad_kalamat(esme_file):
try:
for i in esme_file:
with open(i) as f:
mohtaviat=f.read()
except:
print("no such a file exists")
pass
else:
kalamat=mohtaviat.split()
tedad_kalamat=len(kalamat)
f.close()
print(esme_file , tedad_kalamat ," kalame darad")

您正在尝试将列表传递到函数中,然后想要打开一个完整列表,例如:

with(['/home/wess/tmp/data1.txt','/home/wess/tmp/data2.txt','/home/wess/tmp/data3.txt',])

错了。 创建一个循环并将函数中的每个元素传递给with

最新更新