将内容从源文件传输到目标文件的 Python 程序

萨米特·库马尔 |

我必须编写一个接受两个文件名作为用户输入的程序:源文件名和目标文件名。然后,我必须编写一个函数来将源文件的内容复制到目标文件中。

该程序应该适用于任何大小和类型的文件(甚至像 PDF/PNG 等二进制格式)。

弗朗西斯科·汉纳

为此,您必须考虑任何类型的文件都是由字节“制成”的。您必须从文件中读取字节,然后将此字节复制到另一个文件。

您可以采用 CLI 方法:

# program.py

import sys

# Take second and third elements from the arguments array (first one is 'program.py' itself)
sourceFileName = sys.argv[1]
destFileName = sys.argv[2]

# Open file 'sourceFileName' for reading as binary
sourceFile = open(sourceFileName, "rb") 
data = sourceFile.read()
sourceFile.close()

# Open (or create if does not exists) file 'destFileName' for writing as binary
destFile = open(destFileName, "wb") 
destFile.write(data)
destFile.close()

在这种情况下,您将在命令行中分别将源文件名和目标文件名作为第一个和第二个参数传递,如下所示:

$ python test.py oneFile.txt anotherFile.txt

请注意,onFile.txt应该存在,anotherFile.txt可能存在也可能不存在(如果不存在,它将被创建)

您还可以采用函数式方法:

# program.py

def copyFile(sourceFileName, destFileName):
    # Open file 'sourceFileName' for reading as binary
    sourceFile = open(sourceFileName, "rb") 
    data = sourceFile.read()
    sourceFile.close()

    # Open (or create if does not exists) file 'destFileName' for writing as binary
    destFile = open(destFileName, "wb") 
    destFile.write(data)
    destFile.close()

    print("Done!")

# Ask for file names
src = raw_input("Type the source file name:\n")
dst = raw_input("Type the destination file name:\n")

# Call copyFile function
copyFile(src, dst)

您应该考虑添加一种在打开之前检查源文件是否存在的方法。你可以通过使用os.path.isfile(fileName)函数来做到这一点

希望能帮助到你!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将帮助(tkinter.Tk())的内容传输到python文件

将多个文件从curl传输到其他程序

使用 Python 的 tkinter 将输入字段传输到 Excel 文件

将所有文件以及程序和设置传输到ISO文件

Netbeans:如何将独立Java应用程序的JAR文件自动传输到远程位置

在使用seekg和tellg之前将数据流传输到文件时,程序行为异常

将 CSV 文件传输到 BI 应用程序的正确方法?

应用程序关闭时将文件传输到 Amazon S3

SailsJS:将Facebook应用程序的机密传输到local.js文件

将程序的输出管道传输到动态命名文件(包含日期)

Arelle使用Python将小程序自动化以将数据传输到Excel

如何使用python将大文件从源文件复制到目标文件?

文件程序读写python

JSON文件的Python程序

将python脚本中的值流式传输到wep应用程序

如何使用套接字将文件从 android java 应用程序传输到 C# windows 应用程序?

具有旋转文件内容的Python文件处理程序

在将文件传输到目标位置时取消文件传输

Python-将数据从文件流传输到启用了异步的Kinesis Producer

在Python中使用ftplib将文件传输到FTP服务器时,获得“拒绝连接”

如何使用 Python 通过蓝牙将文件传输到 Android 手机?

自动将文件从多个源文件夹传输到一个目标文件夹

将文件内容管道传输到ls

如何将数据流式传输到希望从作为参数给出的文件中读取数据的程序?

python程序中的.pyw文件

将文件从 S3 Bucket 传输到另一个保存文件夹结构 - python boto

我正在尝试通过 python 程序读取文件的内容

在Python中将git commit哈希管道传输到文件

使用文件控件监视文件的python程序