提问人:bersuperG 提问时间:10/30/2023 最后编辑:bersuperG 更新时间:10/30/2023 访问量:23
任何人都可以帮我编辑我的代码以提取特定的文件名,而不是像现在这样提取文件夹中的所有文件
Can anyone help me edit my code to pull specific file names instead of all the files in the folder like it currently does
问:
只是想弄清楚我错过了什么。我需要此代码将具有特定名称的文件拉取到特定文件夹中,这目前会拉取文件夹中的所有文件。我尝试提取的文件名示例是“USA_2017-10-14_rci_box1.tif”,我想使用文件名中的日期数字来选择它,但如果不是,整个文件名也可以。
#pulls everything from the folder, but not a specific file name string
def movefiles(folder, ctr, stop):
print('moving')
for i in range(0, stop):
day_delta = ctr.date + datetime.timedelta(days=i)
src_fldr = r'path/source/folder' # Replace 'path/source/folder' with the actual source folder path
src_items = os.listdir(src_fldr)
for rci in src_items:
rci_segments = rci.split('_')
output_folder = os.path.join(folder, rci_segments[0])
if ctr.country in rci and str(rci_segments[1]) == str(day_delta):
print(rci)
local_filename = os.path.join(output_folder, 'del{}'.format(rci))
try:
shutil.copy(os.path.join(src_fldr, rci), local_filename)
except Exception as e:
print(f'Error: {str(e)}')
out_rast = os.path.join(folder, r'{}\{}'.format(rci_segments[0], rci))
ctr.rasters.append([local_filename, out_rast])
if str(rci_segments[1]) == str(ctr.date + datetime.timedelta(days=1)):
ctr.mosaic.append(out_rast)
print('-------------')
return
我尝试了文件中的 for 文件循环,但我认为我写得不正确,因为它仍然拉取了文件夹中的所有文件。没有收到错误消息,但它没有按照我的预期运行。
答:
0赞
yinda_peng
10/30/2023
#1
也许这些错误导致了您的问题: 匹配文件名时,您尝试使用“str (rci_segments [1])==str (day_delta)”进行比较。这会将文件名片段与日期对象进行比较,而不是将日期字符串进行比较。然后你执行'shutil。copy“和”ctr. masters.追加“每次迭代,而不仅仅是在找到匹配的文件名时。
评论
0赞
bersuperG
10/30/2023
感谢您的评论!我对 python 还很陌生,但我如何让它与日期字符串进行比较呢?
0赞
bersuperG
10/31/2023
更新:多亏了您的帮助,我才弄清楚了我的问题,即使我每次迭代都执行了 shutil.copy,我不得不像您提到的那样更改比较。再次感谢!
评论