Py学习  »  Python

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

Ratha • 4 年前 • 885 次点击  

我尝试在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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38076
 
885 次点击  
文章 [ 1 ]  |  最新文章 4 年前
junfeng qin
Reply   •   1 楼
junfeng qin    5 年前

您可以参考源代码

    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)