python结果显示了比我预期的不同的东西

python结果显示了比我预期的不同的东西,python,Python,我已经编写了这段代码,但是结果返回没有这样的文件存在,即使所有文件都存在 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: kalama

我已经编写了这段代码,但是结果返回
没有这样的文件存在
,即使所有文件都存在

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',])
这是错误的。
创建一个循环,并使用

传递函数
中的每个元素,如果文件与python脚本不在同一目录中,则可能会出现此错误。更好的办法是指定文件的完整路径。删除try/except/else,以便查看实际错误是什么。。。并修复代码段的缩进。我很确定您需要将esme_文件设置为“esme_文件”,并将文件类型添加到ex..txt、.csv等结尾。您正在使用文件列表而不是每个文件调用函数。更改为shomaresh\u tedad\u kalamat(esm)
。另外,将
一起使用的目的是避免使用
try/except
..@Tomerikoo,将
上下文管理器一起使用是为了消除关闭文件的需要,而不是避免使用try/except