I'd try mapping the share to an unused drive letter by calling the NET USE command using os.system (assuming you are on Windows):os.system(r"NET USE P: \\ComputerName\ShareName %s /USER:%s\%s" % (password, domain_name, user_name))将共享映射到驱动器号后,可以使用shutil.copyfile将文件复制到给定的驱动器.最后,您应该卸载共享:After you mapped the share to a drive letter, you can use shutil.copyfile to copy the file to the given drive. Finally, you should unmount the share:os.system(r"NET USE P: /DELETE")当然,这仅在Windows上有效,并且您必须确保驱动器号P可用.您可以检查NET USE命令的返回码,以查看安装是否成功;否则,请执行以下操作.如果没有,您可以尝试其他驱动器号,直到成功.Of course this works only on Windows, and you will have to make sure that the drive letter P is available. You can check the return code of the NET USE command to see whether the mount succeeded; if not, you can try a different drive letter until you succeed.由于两个NET USE命令是成对出现的,并且第二个命令应始终在执行第一个命令时执行(即使两者之间的某个地方引发了异常),因此如果出现以下情况,可以将这两个调用包装在上下文管理器中:您使用的是Python 2.5或更高版本:Since the two NET USE commands come in pair and the second one should always be executed when the first one was executed (even if an exception was raised somewhere in between), you might wrap these two calls in a context manager if you are using Python 2.5 or later:from contextlib import contextmanager@contextmanagerdef network_share_auth(share, username=None, password=None, drive_letter='P'): """Context manager that mounts the given share using the given username and password to the given drive letter when entering the context and unmounts it when exiting.""" cmd_parts = ["NET USE %s: %s" % (drive_letter, share)] if password: cmd_parts.append(password) if username: cmd_parts.append("/USER:%s" % username) os.system(" ".join(cmd_parts)) try: yield finally: os.system("NET USE %s: /DELETE" % drive_letter)with network_share_auth(r"\\ComputerName\ShareName", username, password): shutil.copyfile("foo.txt", r"P:\foo.txt") 这篇关于如何使用Python将文件复制到网络路径或驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-29 22:39
查看更多