[英]Transfer files from one directory to another if they match a condition using python
I need to use python to move/copy files from one directory to another in UNIX if the filenames match a certain condition, eg filename1 = extra_filename2. 如果文件名符合特定条件,例如,filename1 = extra_filename2,则需要使用python在UNIX中将文件从一个目录移动/复制到另一个目录。 I have prepared the below script but its giving errors.
我已经准备了以下脚本,但是它给出了错误。 Can somebody correct me please:
有人可以纠正我吗:
#!/usr/bin/python
import shutil, fnmatch, os
for filename in os.listdir('/home/root/Desktop/'):
try:
file1 = fnmatch.fnmatch(filename, '*.txt')
file2 = fnmatch.fnmatch(filename, '*.txt')
if file1 = extra_'file2'
print "True"
shutil.copy2('/home/root/Desktop/file1','/home/root/Desktop/Archive',follow_symlinks=True)
import shutil,glob
for fname in glob.glob("/path/to/some*.txt"):
shutil.copy("/dest/path",fname)
Thank you all for your response, my apologies that i couldnt convey my query and i just provided a raw code, it was absolutely wrong. 谢谢大家的答复,我很抱歉无法传达我的查询,而我只是提供了原始代码,这是绝对错误的。 Basically i was looking for something like below :
基本上我正在寻找类似下面的东西:
import os import shutil import re 导入OS导入Shutil导入重新
source = ("sourcePath") 来源=(“ sourcePath”)
files = os.listdir(source) 文件= os.listdir(源)
for name in files: fullpath = source + "/" + name Name2 = name + "filename2" #print fullpath if re.match("filename regex", name) and Name2 in files: 用于文件中的名称:fullpath =源+“ /” +名称Name2 =名称+“ filename2”#如果文件中有re.match(“ filename regex”,name)和Name2,则打印全路径:
#shutil.rmtree("destinationPath"+name) shutil.copytree(fullpath, "destinationpath"+name) shutil.copytree(fullpath, "destinationpath"+Name2)
print "Finished" 打印“完成”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.