Python でファイルをコピーするにはどうすればよいですか?
-
02-07-2019 - |
質問
Python でファイルをコピーするにはどうすればよいですか?
以下には何も見つかりませんでした os
.
解決
shutil
には使用できるメソッドがたくさんあります。そのうちの 1 つは次のとおりです。
from shutil import copyfile
copyfile(src, dst)
という名前のファイルの内容をコピーします src
という名前のファイルに dst
. 。宛先の場所は書き込み可能である必要があります。それ以外の場合は、 IOError
例外が発生します。もし dst
すでに存在する場合は置き換えられます。キャラクタデバイスやブロックデバイス、パイプなどの特殊なファイルは、この機能ではコピーできません。 src
そして dst
は文字列として指定されたパス名です。
他のヒント
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│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
新しいファイルの作成に使用されます。 - 元の変更とアクセス情報 (mtime と atime) がファイルのメタデータに保存されます (ただし、これにはわずかなオーバーヘッドが伴います)。
以下に短い例を示します。
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.ext
次のいずれかのコピー機能を使用できます。 shutil
パッケージ:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Function preserves supports accepts copies other permissions directory dest. file obj metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― シャティル.コピー ✔ ✔ ☐ ☐ シャティル.コピー2 ✔ ✔ ☐ ✔ shutil.コピーファイル ☐ ☐ ☐ ☐ shutil.copyfileobj ☐ ☐ ✔ ☐ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
例:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
以下の例に示すように、ファイルのコピーは比較的簡単な操作ですが、代わりに 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)
Python では、次を使用してファイルをコピーできます。
shutil
モジュールos
モジュールsubprocess
モジュール
import os
import shutil
import subprocess
1) ファイルをコピーする shutil
モジュール
shutil.copyfile
サイン
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)
2) ファイルをコピーする 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')
3) ファイルをコピーする subprocess
モジュール
subprocess.call
サイン
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)
使用 シャティルモジュール.
copyfile(src, dst)
src という名前のファイルの内容を dst という名前のファイルにコピーします。宛先の場所は書き込み可能である必要があります。そうしないと、IOError 例外が発生します。dst がすでに存在する場合は、置き換えられます。キャラクタデバイスやブロックデバイス、パイプなどの特殊なファイルは、この機能ではコピーできません。src と dst は文字列として指定されたパス名です。
を見てみましょう ファイルシステム 標準の Python モジュールで使用できるすべてのファイルおよびディレクトリ処理関数に対応します。
ディレクトリとファイルのコピーの例 - Tim Golden の Python Stuff より:
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"
使用できます os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
あるいは私がやったように、
os.system('cp '+ rawfile + ' rawdata.dat')
どこ rawfile
はプログラム内で生成した名前です。
これは Linux のみのソリューションです
ファイルが小さく、Python 組み込みのみを使用する場合は、次のワンライナーを使用できます。
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
@maxschlepzig が以下のコメントで述べているように、これはファイルが大きすぎるアプリケーションやメモリが重要なアプリケーションには最適な方法ではありません。 スワティの 答えが優先されるべきです。
まず、参考までに 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 をルートとするディレクトリ ツリー全体を再帰的にコピーし、宛先ディレクトリを返します。
大きなファイルの場合は、ファイルを 1 行ずつ読み取り、各行を配列に読み取りました。次に、配列が特定のサイズに達したら、それを新しいファイルに追加します。
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
from subprocess import call
call("cp -p <file> <file>", shell=True)
現在 Python 3.5 小さなファイルの場合は次のことができます (つまり:テキスト ファイル、小さい JPEG):
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
宛先の場所にあったものはすべて上書きされます
open(destination, 'wb').write(open(source, 'rb').read())
ソース ファイルを読み取りモードで開き、宛先ファイルに書き込みモードで書き込みます。
Python には、オペレーティング システム シェル ユーティリティを使用してファイルを簡単にコピーするための組み込み関数が用意されています。
ファイルをコピーするには次のコマンドを使用します
shutil.copy(src,dst)
次のコマンドは、メタデータ情報を含むファイルをコピーするために使用されます
shutil.copystat(src,dst)