【问题标题】:os.rename() error no such file or folder existsos.rename() 错误不存在这样的文件或文件夹
【发布时间】:2015-01-15 12:32:43
【问题描述】:

我一直在尝试创建一个 python 脚本,将我的数据记录到一个名为“log.dat”的 .dat 文件中,并且每分钟将 log.dat 重命名为其他名称,然后开始将传入的日志数据写入一个新的,空 log.dat 文件。

但是我的 os.rename 行正在创建一个错误,我一直在尝试调试它很长时间,但它没有帮助。我一直收到同样的错误说

Error : Traceback (most recent call last):rov sel.:0; homenet:0(-1); current net:0;
 File "tracer.py", line 56, in <module>
main()
File "tracer.py", line 44, in main
os.rename("/home/debian/fname", "/home/debian/log-{}.dat".format(time.strftime("%y%m%d%H%M%S")))
OSError: [Errno 2] No such file or directory

这是我的代码:

from __future__ import print_function
def main():


#!/usr/bin/python
# get lines of text from serial port, save them to a file


    import serial, io
    import time
    import os

    s = open('log.dat', 'w')
    log = time.strftime("%Y%m%d-%H%M%S")
    s = open(log + '.dat', 'w')

    delete = 'cat /dev/null > log.dat'

    addr  = '/dev/ttyACM0'  # serial port to read data from
    baud  = 9600            # baud rate for serial port
    fname = 'log.dat'   # log file to save data in
    fmode = 'a'             # log file mode = append

    with serial.Serial(addr,9600) as pt, open(fname,fmode) as outf:
        spb = io.TextIOWrapper(io.BufferedRWPair(pt,pt,1),
            encoding='ascii', errors='ignore', newline='\r',line_buffering=$
        spb.readline()
        while (1):
            now = time.time()
            with open(fname,fmode) as outf:
                while (time.time() - now) < 60:
                      x = spb.readline()  # read one line of text from serial$
                      print (x,end='')    # echo line of text on-screen
                      outf.write(x)       # write line of text to file
                      outf.flush()        # make sure it actually gets written
                      os.rename("/home/debian/fname", "/home/debian/log-           
                                {}.dat".format(time.strftime("%y%m%d%H%M%S")))

if __name__ == '__main__':

main()

我不明白我在这里做错了什么。 非常感谢任何建议或帮助。

【问题讨论】:

  • 你试过os.rename("/home/debian/log.dat" ... ,因为你说你需要重命名log.dat
  • 是的,我做到了。但它仍然给我同样的错误。

标签: python linux debian


【解决方案1】:

试试:

os.rename("/home/debian/"+fname, "/home/debian/log-           
{}.dat".format(time.strftime("%y%m%d%H%M%S")))

或:

os.rename("/home/debian/log.dat", "/home/debian/log-                             
{}.dat".format(time.strftime("%y%m%d%H%M%S")))

【讨论】:

    【解决方案2】:

    您没有在open 调用中指定绝对路径;我们不知道当前目录是否真的是/home/debian;因此在os.rename 中使用绝对路径是不明智的。宁可写

    os.rename(fname, "log-{}.dat".format(time.strftime("%y%m%d%H%M%S")))
    

    使用与open 相同的名称。

    【讨论】:

      猜你喜欢
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 2016-01-09
      • 1970-01-01
      • 2023-04-01
      • 2014-02-19
      相关资源
      最近更新 更多