将内容从源文件传输到目标文件的Python程序
我必须编写一个程序,接受两个文件名作为用户的输入:一个源文件名和一个目标文件名。然后,我必须编写一个函数,将源文件的内容复制到目标文件中将内容从源文件传输到目标文件的Python程序,python,Python,我必须编写一个程序,接受两个文件名作为用户的输入:一个源文件名和一个目标文件名。然后,我必须编写一个函数,将源文件的内容复制到目标文件中 程序应该使用任何大小和类型的文件(甚至二进制格式,如PDF/PNG等)。您必须从文件中读取字节,然后将这些字节复制到另一个文件中 您可以采用CLI方法: # program.py import sys # Take second and third elements from the arguments array (first one is 'progr
<>程序应该使用任何大小和类型的文件(甚至二进制格式,如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()
# 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)
在本例中,您将在命令行中分别将源文件名和目标文件名作为第一个参数和第二个参数传递,如下所示:
$ python test.py oneFile.txt anotherFile.txt
请注意,onFile.txt
应该存在,anotherFile.txt
可能存在,也可能不存在(如果不存在,将创建它)
您也可以采用功能性方法:
# 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()
# 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(文件名)
函数来实现这一点
希望有帮助 谢谢你给我们你的家庭作业,但这不是合适的地方。你自己试试,如果没有成功,给我们你的代码,我们会尽力帮助你。明白了!从今以后我会记住:)这真的很清楚,很有帮助!感谢you@SamithKumar不客气!如果对你有帮助的话,请选择我的答案作为对这个问题的回答。这个解决方案有一些缺点。如果有一个大文件(假设为100gb),它将尝试一次读取整个文件并将其加载到主内存中。主内存不能一次处理这么大的文件,因为它们通常在8gb到16gb之间。你能给我一个更好的答案吗?我们可以找出文件的总大小,然后一次复制一大块?