回答:
shutilあなたが使用できる多くの方法があります。その1つは次のとおりです。
from shutil import copyfile
copyfile(src, dst)os.path操作を使用する場合copyは、ではなくを使用してくださいcopyfile。copyfileう文字列のみを受け入れます。
~は処理できませんが、相対パスは処理できます
                    ┌──────────────────┬────────┬───────────┬───────┬────────────────┐
│     Function     │ Copies │   Copies  │Can use│   Destination  │
│                  │metadata│permissions│buffer │may be directory│
├──────────────────┼────────┼───────────┼───────┼────────────────┤
│shutil.copy       │   No   │    Yes    │   No  │      Yes       │
│shutil.copyfile   │   No   │     No    │   No  │       No       │
│shutil.copy2      │  Yes   │    Yes    │   No  │      Yes       │
│shutil.copyfileobj│   No   │     No    │  Yes  │       No       │
└──────────────────┴────────┴───────────┴───────┴────────────────┘copy2(src,dst)多くの場合、次のcopyfile(src,dst)理由よりも便利です。
dstであることがディレクトリ(代わりの完全なターゲットファイル名)、その場合、ベース名のsrc新しいファイルを作成するために使用されます。以下に短い例を示します。
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.extcopyfileかなり速くよりcopy2
                    shutil.copy2('/dir/file.ext', '/new/dir/')「DIR」と呼ばれる新しいファイルにコピーするか、その名前のディレクトリにファイルを配置するかどうかの上にあいまいさを削除します(ターゲットパスの後にスラッシュ)?
                    /new/dir既存のディレクトリである場合、あいまいさはありません。@ MatthewAlpertのコメントを参照してください。
                    /new/dir/存在しない、PythonがスローされますIsADirectoryErrorし、それ以外の場合はコピーしたファイルを/new/dir/元の名前の下に。
                    shutilパッケージのコピー機能の1つを使用できます。
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
機能はサポートを支持します他のコピーを受け入れます
                      権限ディレクトリdest。ファイルobjメタデータ  
―――――――――――――――――――――――――――――――――――――――――――――――――― ――――――――――――――――――――――――――――
shutil.copy               ✔✔☐☐
 shutil.copy2              ✔✔☐✔
 shutil.copyfile           ☐☐☐☐
 shutil.copyfileobj        ☐☐✔☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
例:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')Pythonでは、次を使用してファイルをコピーできます。
shutil モジュールos モジュールsubprocess モジュールimport os
import shutil
import subprocessshutilモジュールを使用してファイルをコピーするshutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example    
shutil.copyfile('source.txt', 'destination.txt')shutil.copy  署名
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')shutil.copy2  署名
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')  shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'  
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'  
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)  osモジュールを使用してファイルをコピーするos.popen  署名
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt') 
# In Windows
os.popen('copy source.txt destination.txt')os.system  署名
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')  
# In Windows
os.system('copy source.txt destination.txt')subprocessモジュールを使用してファイルをコピーするsubprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True) 
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)['copy', sourcefile, destfile]、特にパラメーターがユーザー入力からのものである場合は、可能な限り構文を使用してください。
                    os.popenしばらくは非推奨です。そしてcheck_outputステータスが、(の場合には空である出力戻らないcopy/cp)
                    以下の例に示すように、ファイルのコピーは比較的簡単な操作ですが、代わりにshutil stdlibモジュールを使用する必要があります。
def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)ファイル名でコピーしたい場合は、次のようにします。
def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)shutil.copyfileobj。また、try, finally例外後のファイルのクローズを処理する必要はありません。ただし、関数はファイルを開いたり閉じたりする必要はありません。これは、shutil.copyfilewrapsのようなラッパー関数に入れるべきshutil.copyfileobjです。
                    dest書き込み可能に指定する必要があります:open(dest, 'wb')
                    shutilモジュールを使用します。
copyfile(src, dst)srcという名前のファイルの内容をdstという名前のファイルにコピーします。宛先の場所は書き込み可能でなければなりません。それ以外の場合は、IOError例外が発生します。dstがすでに存在する場合は、置き換えられます。キャラクターデバイスやブロックデバイス、パイプなどの特殊ファイルは、この関数ではコピーできません。srcおよびdstは、文字列として指定されたパス名です。
見てみましょうのfilesys標準のPythonモジュールで使用可能なすべてのファイルとディレクトリの取り扱い機能のために。
ディレクトリとファイルのコピー例-Tim GoldenのPythonスタッフから:
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"まず、参考のために、shutilメソッドの完全なチートシートを作成しました。
shutil_methods =
{'copy':['shutil.copyfileobj',
          'shutil.copyfile',
          'shutil.copymode',
          'shutil.copystat',
          'shutil.copy',
          'shutil.copy2',
          'shutil.copytree',],
 'move':['shutil.rmtree',
         'shutil.move',],
 'exception': ['exception shutil.SameFileError',
                 'exception shutil.Error'],
 'others':['shutil.disk_usage',
             'shutil.chown',
             'shutil.which',
             'shutil.ignore_patterns',]
}次に、例としてコピーの方法を説明します。
shutil.copyfileobj(fsrc, fdst[, length])開いたオブジェクトを操作する
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
    ...:      shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)コピーして名前を変更
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()メタデータを事前に提示せずにコピーする
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()メタデータを事前にコピーしてコピー
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
shutil.copytree()
srcをルートとするディレクトリツリー全体を再帰的にコピーし、宛先ディレクトリを返します
小さなファイルでpython組み込みのみを使用する場合は、次のワンライナーを使用できます。
with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())@maxschlepzigが以下のコメントで言及されているように、これはファイルが大きすぎるアプリケーションやメモリが重要な場合の最適な方法ではないため、Swatiの回答をお勧めします。
.read()と.write()(少なくとも、CPythonのための)デフォルトではバッファリングされています。
                    open()がデフォルトでバッファIOを実行するという事実は、次のようにread()指定されているため、ここでは役に立ちません。「nが負であるか省略されている場合は、EOFまで読み取ります。」つまり、read()は完全なファイルコンテンツを文字列として返します。
                    あなたは使うことができます os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
または私がやったように、
os.system('cp '+ rawfile + ' rawdata.dat')rawfileプログラム内で生成した名前はどこですか。
これはLinuxのみのソリューションです
shutilが利用できない場合でも- subprocess.run()  (なしshell=True!)がのより良い代替手段os.system()です。
                    subprocess.run()@maxschlepzigによって提案されているように、外部プログラムを呼び出すときは大きな前進です。ただし、柔軟性とセキュリティのために['cp', rawfile, 'rawdata.dat']、コマンドラインを渡す形式を使用します。(ただし、コピーにshutilは、外部プログラムを呼び出すよりも友人をお勧めします。)
                    大きなファイルの場合、ファイルを1行ずつ読み取り、各行を配列に読み込みました。次に、配列が特定のサイズに達したら、新しいファイルに追加します。
for line in open("file.txt", "r"):
    list.append(line)
    if len(list) == 1000000: 
        output.writelines(list)
        del list[:]for l in open('file.txt','r'): output.write(l)機能するはずです。必要に応じて出力ストリームバッファをセットアップするだけです。または、一度に書き込みたいバイト数がoutput.write(read(n)); output.flush()どこnであるかを試行してループすることにより、バイト単位で移動できます。これらはどちらもボーナスであるかどうかをチェックする条件がありません。
                    shutilか?を無視shutilする場合でも、単純なブロックの読み取り/書き込みループ(バッファリングされていないIOを使用)は単純であり、効率的であり、これよりもはるかに理にかなっているため、教えることと理解することは確かに簡単です。
                    from subprocess import call
call("cp -p <file> <file>", shell=True)callは安全ではありません。それについては、サブプロセスのドキュメントを参照してください。
                    以下のようPythonの3.5あなたは小さなファイル(テキストファイル、JPEGファイル小さなIE)のために、以下の操作を行うことができます。
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())write_bytes 宛先の場所にあったものを上書きします
shutil、すべての特殊なケースに対応し、安心できます。
                    open(destination, 'wb').write(open(source, 'rb').read())ソースファイルを読み取りモードで開き、書き込みモードで宛先ファイルに書き込みます。
.close()それらすべてのopen(...)s が欠けていませんか?
                    Pythonには、オペレーティングシステムシェルユーティリティを使用してファイルを簡単にコピーするための組み込み関数が用意されています。
次のコマンドを使用してファイルをコピーします
shutil.copy(src,dst)次のコマンドを使用して、メタデータ情報を含むファイルをコピーします
shutil.copystat(src,dst)copy次に実行copystatして、ファイルのメタデータを保持する必要があります。Python 3.3以降でcopystatは、拡張属性もコピーされます。