假设我有一个文本文件aiq_hits.txt
。
此文件中的每一行对应一个文件名
ant1.aiq
ant2.aiq
ant3.aiq
ant4.aiq
我希望将文本文件的每一行(ant1.aiq,ant2.aiq等)与存在于某个特定位置(R:\Sample
)的文件名匹配,并将匹配文件提取到其他位置({ {1}})。
我知道我需要使用R:\sample\wsa
和os.walk()
,fnmatch.fnmatch()
等功能,但我无法实现它们
我的代码:
shutil.copy()
我被困在这里
答案 0 :(得分:0)
import os
import shutil
sourceDir = "R:\\Sample"
targetDir = "R:\\Sample\\wsa"
existingFiles = set(f for f in os.listdir(sourceDir) if os.path.isfile(os.path.join(sourceDir, f)))
infilepath = "aiq_hits.txt"
with open(infilepath) as infile:
for line in infile:
fname = line.strip()
if fname not in existingFiles: continue
shutil.move(os.path.join(sourceDir, fname), os.path.join(targetDir, fname))
答案 1 :(得分:0)
我希望这就足够了:
import os
def match_files(url,file_read, dest):
f = open(file_read, 'rb')
file_list = os.listdir(url)
print(file_list)
saved_path = os.getcwd()
print("Current working directory is " + saved_path)
os.chdir(url)
match = []
for file_name in f:
file_name = file_name.strip()
if file_name in file_list:
match.append(file_name)
os.rename(os.path.join(url, file_name), os.path.join(dest, file_name))
os.chdir(saved_path)
print match

这里,url是你想要匹配文件的源目录或文件夹,file_read是文件名(带路径),其中给出了文件名列表,dest是目标文件夹。 此代码将匹配文件从url移动到dest,即这些文件在运行代码后不会在url中提醒。
答案 2 :(得分:0)
或者你可以使用glob模块,它允许你输入文件名\ extension的表达式,然后返回一个你可以循环的列表。
如果源目录可以包含您要排除的相同扩展名的文件,则我将使用此模块
此外,我假设文件名列表不大,因此将其存储在列表中不会有问题
例如(我还未经过以下测试)
from glob import glob
import os
import shutil
src = 'R:\\Sample'
dst = "R:\\Sample\\wsa"
in_file_list = "aiq_hits.txt"
list_Of_files = glob(os.path.join(src, 'ant*.aiq'))
data = []
with open(in_file_list) as reader:
data += reader.readlines()
for row in list_Of_files:
file_path, file_name = os.path.split(row)
if file_name in data:
shutil.copy2(row, os.path.join(dst, file_name))
# or if you want to move the file
# shutil.move(row, os.path.join(dst, file_name))