1

我想在 Windows 上使用 Python 将文本文件发送到网络打印机。我无法正确格式化我的目标字符串。这种方法:

shutil.copy(fileName, '\\server\printer')

吐出这个错误:

FileNotFoundError: [Errno 2] No such file or directory: '\\server\\printer'

第二个反斜杠到底是从哪里来的?

我可以从命令提示符成功复制文件,这将我的问题缩小到这种shutil.copy()方法。我一直在研究字符串、字符串表示、转义字符和 UNC 路径,但没有成功。

也许我们应该像这样逃避那些反斜杠?

shutil.copy(fileName, '\\\\server\\printer')

不,也许我们应该尝试这样的原始字符串?

shutil.copy(fileName, r'\\server\printer')

不,那行不通。我想我不太了解目标字符串如何在幕后移动或在执行此操作时的样子,而且我不确定如何找出答案。也许我应该深入研究shutil.copy()方法?好让我们看看,

def copyfile(src, dst, *, follow_symlinks=True):
    """Copy data from src to dst.

    If follow_symlinks is not set and src is a symbolic link, a new
    symlink will be created instead of copying the file it points to.

    """
    if _samefile(src, dst):
        raise SameFileError("{!r} and {!r} are the same file".format(src, dst))

    for fn in [src, dst]:
        try:
            st = os.stat(fn)
        except OSError:
            # File most likely does not exist
            pass
        else:
            # XXX What about other special files? (sockets, devices...)
            if stat.S_ISFIFO(st.st_mode):
                raise SpecialFileError("`%s` is a named pipe" % fn)

    if not follow_symlinks and os.path.islink(src):
        os.symlink(os.readlink(src), dst)
    else:
        with open(src, 'rb') as fsrc:
            with open(dst, 'wb') as fdst:
                copyfileobj(fsrc, fdst)
    return dst

看到这样的事情,我什至不知道从哪里开始,对于这样一个无害的错误,这似乎比我能承受的更令人头疼。

4

0 回答 0