def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
On Windows, 'b' appended to the mode opens the file in binary mode, so
there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows
makes a distinction between text and binary files; the end-of-line
characters in text files are automatically altered slightly when data
is read or written. This behind-the-scenes modification to file data
is fine for ASCII text files, but it’ll corrupt binary data like that
in JPEG or EXE files. Be very careful to use binary mode when reading
and writing such files. On Unix, it doesn’t hurt to append a 'b' to
the mode, so you can use it platform-independently for all binary
files.
您应该使用^{} 或^{} ,这样可以有效、正确地使用缓冲区。在
并不是说它特别难,
shutil.copyfileobj()
被实现为:这可以确保你的内存不会被一个大文件填满,而是通过分块读取该文件。另外,
.read()
不能保证返回文件的所有数据,如果在.read()
返回空字符串之前不循环,则可能无法复制所有数据。在如果以二进制模式打开这两个文件,则使用.read()读取,然后使用write()写入,则会得到完全相同的副本。如果使用其他机制,则可能会去掉行结尾或遇到问题,特别是在跨平台工作时。在
从文件中
在任何情况下,使用其他方法来进行文件复制,就像其他人建议的那样。在
一个警告是,
.read()
不一定保证一次读取整个文件,因此必须确保重复读/写循环,直到所有数据都被复制。另一个原因是可能没有足够的内存一次读取所有数据,在这种情况下,您需要执行多次部分读写操作才能完成复制。在相关问题 更多 >
编程相关推荐