代码之家  ›  专栏  ›  技术社区  ›  Ratha

或者.rename(src,dest)throws文件在python中没有错误

  •  0
  • Ratha  · 技术社区  · 7 年前

    我尝试在sftp服务器中远程重命名文件。 这是我的密码;

     srv = pysftp.Connection(host=host, username=username, password=password, port=port, cnopts=connOption)
        # Get the directory and file listing
        data = srv.listdir()
    
        try:
            for infile in data:
                if infile == filename:
                    infile_without_ext = os.path.splitext(infile)[0]
                    extension = os.path.splitext(infile)[1]
                    new_file_name = infile_without_ext + "_" + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    new_file_name_with_ext = new_file_name + extension
    
                    print infile   //<----printing the file
                    print new_file_name_with_ext
    
                    os.rename(infile,  new_file_name_with_ext)
    

    当我打印时 infile 它打印文件。但当我尝试重新命名时,我会出错;

    OSError: [Errno 2] No such file or directory
    

    我的文件在根目录中。 我怎么解决这个问题?

    0 回复  |  直到 7 年前
        1
  •  -1
  •   junfeng qin    7 年前

    您可以参考源代码

        def rename(self, remote_src, remote_dest):
        """rename a file or directory on the remote host.
    
        :param str remote_src: the remote file/directory to rename
    
        :param str remote_dest: the remote file/directory to put it
    
        :returns: None
    
        :raises: IOError
    
        """
        self._sftp_connect()
        self._sftp.rename(remote_src, remote_dest)