我有一些照片和一些视频,我必须将它们复制到另一个文件夹中,而不使用
shutil
和 os.rename
。 我无法使用 Shutil 和 os.rename,因为这是该 Python 练习的条件。我尝试了open
,但它只适用于文本,不适用于照片和视频。
以二进制方式打开文件,并以二进制方式写入
original_file = open('C:\original.png', 'rb') # rb = Read Binary
copied_file = open('C:\original-copy.png', 'wb') #wb = Write Binary
copied_file.write(original_file.read())
original_file.close()
copied_file.close()
pathlib
:
from pathlib import Path
Path("old_file.png").write_bytes(Path("new_file.png").read_bytes())
@X3R0的回答就够了;我想分享一个更完整的代码
def readfile(file="uid.txt", mod="r", cont=None, jso: bool = False):
if not mod in ("w", "a", "wb", ):
assert os.path.isfile(file), str(file)
assert cont is None
if mod == "r":
with open(file, encoding="utf-8") as file:
lines: list = file.readlines()
return lines
elif mod == "_r":
with open(file, encoding="utf-8") as file:
contents = file.read() if not jso else json.load(file)
return contents
elif mod == "rb":
with open(file, mod) as file:
contents = file.read()
return contents
else:
fil_e = open(file, mod, encoding="utf-8") if not mod == "wb" else open(file, mod)
if not jso:
fil_e.write(cont)
else:
assert not mod == "wb"
json.dump(cont, fil_e, indent=2, ensure_ascii=False)
fil_e.close()
cont = readfile(file='C:\original.bla', mod="rb")
readfile(file='C:\original-copy.bla', mod="wb", cont=cont)