Python:IOError:[Errno 2]没有这样的文件或目录(Raspberry PI)

时间:2013-12-15 11:42:16

标签: python raspberry-pi

我正在尝试编写一个输出文本文件的程序;它会在我执行时重命名。

然而我无法执行它。错误消息[IOError: Errno 2 No such file or directory]

这是我的代码:

from Adafruit_BMP085 import BMP085
from time import sleep
import time
import datetime
import pickle, sys, os

while True:     

class data():
    def __init__(self):
        self.tp = tps()
        self.savedata()

    def savedata(self):             
        now = datetime.datetime.now()
        timestamp = now.strftime("%Y/%m/%d %H:%M:%S")
        filename= 'Temperature_'+ timestamp +'.txt'

        f=open (filename,'a')

        timestamp = now.strftime("%Y/%m/%d %H:%M:%S")

        self.tp.updateTempAndPressure()

        outvalue  = self.tp.temp 
        outvalue_1= self.tp.altitude
        outvalue_2= self.tp.pressure/100            

        outstring = str(timestamp)+" Temperature:"+str(outvalue)+ " C Altitude: "+str(outvalue_1)+ "m Pressure: " +str(outvalue_2)+ "hPa" + "\n"

        print outstring
        f.write(outstring)
        f.close()

data()  
time.sleep(1)

有没有我想念它的功能?我的代码还有什么问题导致我无法完成整个任务吗?

提前致谢

1 个答案:

答案 0 :(得分:3)

以下语句创建一个类似'2013/12/15 20:44:59

的字符串
timestamp = now.strftime("%Y/%m/%d %H:%M:%S")

/是unix中的路径名分隔符。要创建文件,您需要中间目录。

>>> open('1/2/3', 'a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '1/2/3'
>>> open('1-2-3', 'a')
<open file '1-2-3', mode 'a' at 0xb74bd128>

如何将/更改为-等其他字符?

timestamp = now.strftime("%Y-%m-%d %H:%M:%S")