复制jpg文件时出现Python错误

2024-04-19 06:51:22 发布

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

我已经完成了对txt文件的复制,并尝试对jpg文件执行相同的操作。但我不断地得到一个编码错误。 我的代码是:

def fcopy(source, target):
data = ''
with open(source, encoding='Latin-1') as f:
    data = f.read()
    with open(target, 'w') as t:
            t.write(data)
fcopy("source.jpeg","dest.jpeg")

我也尝试过使用encoding=utf8和utf16。但不起作用,错误如下:

Traceback (most recent call last):
  File "C:/Users/Mark-II/Desktop/fileCopy.py", line 7, in <module>
    fcopy("source.jpeg","dest.jpeg")
  File "C:/Users/Mark-II/Desktop/fileCopy.py", line 3, in fcopy
    with open(source, encoding='Latin-1') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'source.jpeg'
>>> 

请帮忙。你知道吗


Tags: 文件sourcetargetdataas错误withopen
2条回答

代码正在运行。你的问题是文件路径。请检查您提供的图像路径。你知道吗

尝试以“二进制模式”打开文件。根据open方法的文档,默认为文本模式。这就解释了为什么它在文本文件上工作而在非文本文件(如jpg图像)上失败。以二进制模式打开文件时,不需要使用命名参数进行编码。你知道吗

def fcopy(source, target):
    with open(source, 'rb') as f:
        data = f.read()
    with open(target, 'wb') as t:
        t.write(data)

fcopy("source.jpeg","dest.jpeg")

相关问题 更多 >