python无法读取存在的文件

python无法读取存在的文件,python,Python,我写了下面的脚本 #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt ######## N = 92 lookup = 'The forecast spread is' iday_start = 1 iday_end = 1 year = 2013 month = 07 extension_type1

我写了下面的脚本

#!/usr/bin/env python 
import numpy as np 
import matplotlib.pyplot as plt 

########
N = 92 
lookup  = 'The forecast spread is'
    iday_start    = 1 
    iday_end      = 1
    year        = 2013
    month       = 07  
    extension_type1  = '-RTPSinfl.dat'
    extension_type2  = 'engl_var_anal.'
    extension        = 2
######### Append the files into files
    for iday in range (iday_start, iday_end+1):
        day =  str(0) + str(iday) 
        for itime in range(0,24,6) :   
           if itime < 12: 
           ihour = str(0) + str(itime)
        else:
           ihour =  str(itime) 
        if extension == 1 :  
          file  = str(year)+str(month) + day + ihour + extension_type1
          print(file)  
        elif  extension == 2 :
          file = extension_type2 + str(year)+str(month)+day+ihour+'.1.out'
          print(file)         
#========          
      f = open(file)
      lines = f.readlines()
      f.close() 
      with open(file) as myFile:
          for num, line in enumerate(myFile,1):
              if lookup in line:
                  print 'found at line:', num  
          num = num+2
          numN = num + N
          lrange = range(num,numN)
          for l in lrange:
                for ii in range(0,7): 
                    nstart = numN + ii * (N+2) + 1
                    lrange = range(nstart,nstart+N)
                    for l in lrange:
                        print lines[l],                 
      myFile.close()

文件engl_var_anal.201370100.1.out不存在

Python将从运行脚本的目录加载文件,而不是从脚本位置加载文件。如果这没有帮助,你能告诉我们你正在运行的确切命令和文件所在的完整路径吗

编辑

需要注意的一点是,文件名中的位数与程序输出的位数完全相同。在处理将数字打印到字符串时,这是一个常见错误。看起来您希望您的月份是2位数字“07”,但您的输出文件名只有1位。再检查一下这个

如果需要2位数字,请执行某种字符串格式设置,如:

file = extension_type2 + "%04d%02d%02d%04d" % (year, month, day, ihour) + ".1.out"
或者使用datetime对象和strftime格式化日期/时间


如果您使用/files\u和脚本
cd/dir/with/files\u和
,然后运行
ls-l
(假设使用linux shell),您会看到“test.py”和“engl\u var\u anal.201370100.1.out”,然后运行
python
,…一些代码…,
execfile(“test.py”)
。这应该可以正常工作。

您的缩进到处都是,你能清理一下吗?一个文件可能存在于你的硬盘上,但不在脚本的当前工作目录中。请使用完整路径。@user3270373:如果您对我的答案感到满意,请单击答案左侧的复选标记接受答案。谢谢,谢谢。我运行脚本并从同一位置加载文件。我在python2.7解释器中使用了以下命令execfile('test.py')。@user3270373:或者您的工作目录不是您所认为的(请尝试
import os;print(os.getcwd())
,文件不存在,或者您的文件系统报告文件不存在时出现了严重问题。前两个选项似乎最有可能。@user3270373查看我的编辑。我认为文件名中的数字可能没有您预期的那么多。
file = extension_type2 + "%04d%02d%02d%04d" % (year, month, day, ihour) + ".1.out"