我必须编写一个接受两个文件名作为用户输入的程序:源文件名和目标文件名。然后,我必须编写一个函数来将源文件的内容复制到目标文件中。
该程序应该适用于任何大小和类型的文件(甚至像 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] 删除。
我来说两句