mal*_*ina 30 python directory move
我想使用Python将所有文本文件从一个文件夹移动到另一个文件夹.我找到了这段代码:
import os, shutil, glob
dst = '/path/to/dir/Caches/com.apple.Safari/WebKitCache/Version\ 4/Blobs '
try:
os.makedirs(/path/to/dir/Tumblr/Uploads) # create destination directory, if needed (similar to mkdir -p)
except OSError:
# The directory already existed, nothing to do
pass
for txt_file in glob.iglob('*.txt'):
shutil.copy2(txt_file, dst)
Run Code Online (Sandbox Code Playgroud)
我希望它移动文件Blob夹中的所有文件.我没有收到错误,但它也没有移动文件.
Shi*_*ndi 50
试试这个..
import shutil
import os
source = '/path/to/source_folder'
dest1 = '/path/to/dest_folder'
files = os.listdir(source)
for f in files:
shutil.move(source+f, dest1)
Run Code Online (Sandbox Code Playgroud)
Dat*_*ice 14
很惊讶这没有使用 python 3.4+ 中引入的 pathilib 的答案
此外,shutil 在 python 中更新,3.6以在此PEP-0519 中接受 pathlib 对象的更多详细信息
from pathlib import Path
src_path = '\tmp\files_to_move'
for each_file in Path(src_path).glob('*.*'): # grabs all files
trg_path = each_file.parent.parent # gets the parent of the folder
each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
Run Code Online (Sandbox Code Playgroud)
from pathlib import Path
import shutil
src_path = '\tmp\files_to_move'
trg_path = '\tmp'
for src_file in Path(src_path).glob('*.*'):
shutil.copy(src_file, trg_path)
Run Code Online (Sandbox Code Playgroud)
小智 6
将“.txt”文件从一个文件夹复制到另一个文件夹非常简单,问题包含逻辑。只有缺失的部分用正确的信息替换如下:
import os, shutil, glob
src_fldr = r"Source Folder/Directory path"; ## Edit this
dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print "Folder already exist or some error";
Run Code Online (Sandbox Code Playgroud)
下面的代码行会将带有 *.txt 扩展名的文件从 src_fldr 复制到 dst_fldr
for txt_file in glob.glob(src_fldr+"\\*.txt"):
shutil.copy2(txt_file, dst_fldr);
Run Code Online (Sandbox Code Playgroud)