使用python复制文件

2024-03-29 15:50:23 发布

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

我对python还比较陌生,并且是“艰难地学习python”的一部分,但是有一个问题。在

所以,从我读到的,如果你想复制一个文本文件,你可以打开它,把它的内容读到一个变量,然后把这个变量写到另一个文件。我已经用图像测试过了,它实际上似乎很管用。这种复制方法是否有缺点,我将在后面讨论,是否有任何文件类型是它不适用的?在

非常感谢!在


Tags: 文件方法图像内容文件类型文本文件缺点陌生
3条回答

您应该使用^{}^{},这样可以有效、正确地使用缓冲区。在

并不是说它特别难,shutil.copyfileobj()被实现为:

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)

这可以确保你的内存不会被一个大文件填满,而是通过分块读取该文件。另外,.read()不能保证返回文件的所有数据,如果在.read()返回空字符串之前不循环,则可能无法复制所有数据。在

^{bq}$

如果以二进制模式打开这两个文件,则使用.read()读取,然后使用write()写入,则会得到完全相同的副本。如果使用其他机制,则可能会去掉行结尾或遇到问题,特别是在跨平台工作时。在

从文件中

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.

在任何情况下,使用其他方法来进行文件复制,就像其他人建议的那样。在

一个警告是,.read()不一定保证一次读取整个文件,因此必须确保重复读/写循环,直到所有数据都被复制。另一个原因是可能没有足够的内存一次读取所有数据,在这种情况下,您需要执行多次部分读写操作才能完成复制。在

相关问题 更多 >