How to "copy" a file in python? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to "copy" a file in python? (/thread-2615.html) |
How to "copy" a file in python? - tannishpage - Mar-29-2017 So I am trying to not use shutil or os libraries. So what i tried is: fileOriginal = open(filename, "rb") os.chdir(destination) #In this case destination is a full path. fileDuplicate = open(filename, "wb") fileDuplicate.write(fileOriginal) fileOriginal.close() fileDuplicate.close()This is what i have so far. But this throws this error: TypeError: a bytes-like object is required, not '_io.BufferedReader' How am I supposed to do it using this method. I need this to work for any file type. RE: How to "copy" a file in python? - wavic - Mar-29-2017 fileDuplicate.write(fileOriginal.read()) fileDuplicate is an object. You can't just write it to a file. To get the content of a file object you have to call its method read() Instead of changing the directory you can use os.path.join() method >>> import os.path >>> destination = "Programming/Pycode" >>> file = "2en-adv.py" >>> os.path.join(destination, file) 'Programming/Pycode/2en-adv.py' fileDuplicate = open(filename, "wb")Also, consider using a 'with' statement to open the files. with open(filename, 'rb') as fileOriginal, open(os.path.join(destination, filename), 'wb') as fileDuplicate: fileDuplicate.write(fileOriginal.read())This way Python closes the opened files once the with block is executed RE: How to "copy" a file in python? - tannishpage - Mar-29-2017 Um, what does os.path.join do? I don't understand that part. RE: How to "copy" a file in python? - snippsat - Mar-29-2017 (Mar-29-2017, 08:38 AM)tannishpage Wrote: Um, what does os.path.join do? I don't understand that part.Making a absolute path so Python can read it from file system. >>> import os >>> help(os.path.join) Help on function join in module ntpath: join(a, *p) Join two or more pathname components, inserting "\" as needed. If any component is an absolute path, all previous path components will be discarded. >>> path = 'c:/music/app/' >>> file_name = 'song.mp3' >>> os.path.join(path, file_name) 'c:/music/app/song.mp3' >>> # Linux >>> path = 'music/app/' >>> file_name = 'song.mp3' >>> os.path.join(path, file_name) 'music/app/song.mp3' RE: How to "copy" a file in python? - tannishpage - Mar-29-2017 Ok. Thanks. Your solution worked, and i understand it. |