Python使用shutil在同一网络中传输文件

2024-10-06 12:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在同一网络中的两台服务器(Ubuntu和Windows)之间移动一个.txt文件。 以下代码未显示任何错误,但不起作用:

def transfer_files_task():

    source_path = r"/root/airflow/testdoc"
    dest_path = f"192.168.xxx.xx\Doc-Share\Logger Output"
    filename = r"/test.txt"
    filenamew = f"\test.txt"
    shutil.copyfile(source_path + filename, dest_path + filenamew)

Tags: 文件path代码test网络服务器txtsource
1条回答
网友
1楼 · 发布于 2024-10-06 12:32:28

将您的功能更改为:

import os, ntpath, posixpath

def transfer_files_task(): 
     source_file = posixpath.join("/", "root", "airflow", "testdoc", "test.txt") 
     dest_file = ntpath.join("192.168.xxx.xx", "Doc-Share", "Logger Output", "test.txt")
     assert os.path.exists(source_file), f"{source_file} does not exists"
     shutil.copyfile(source_file, dest_file) 

一个小的解释:让python格式化您的路径,它将使您避免许多错误。如果不这样做,您必须知道字符串是如何工作的,应该转义哪些字符,如何在linux和windows上格式化路径,等等

另外,关于字符串使用rf前缀的旁注:

  • r代表raw,它大致意味着不必转义特殊字符,比如退格。因此,r"\tab" == "\\tab"print(r"\tab")给出\tab,而print("\tab")给出 ab
  • f代表格式,是py36+中格式化字符串的新方法。其用途如下:
name="john"
print(f"hello {name}")
# hello john

最后,您可能想查看以下帖子:Cannot copy file from a remote machine using shutil

相关问题 更多 >