如何在 Python 中将具有随机名称的文件从一个文件夹移动到另一个文件夹?
How can I move files with random names from one folder to another in Python?
我有大量以 "cb" + 数字(如 cb10、cb13)组合命名的 .txt 文件,我需要从包含所有名为在 "cb + number" 中,包括目标文件。
目标文件名中的数字都是随机的,所以我必须列出所有文件名。
import fnmatch
import os
import shutil
os.chdir('/Users/college_board_selection')
os.getcwd()
source = '/Users/college_board_selection'
dest = '/Users/seperated_files'
files = os.listdir(source)
for f in os.listdir('.'):
names = ['cb10.txt','cb11.txt']
if names in f:
shutil.move(f,dest)
if names in f:
不会起作用,因为 f
是文件名,而不是列表。也许你想要 if f in names:
但是你不需要为此扫描整个目录,只需循环你的目标文件,如果它们存在:
for f in ['cb10.txt','cb11.txt']:
if os.path.exists(f):
shutil.move(f,dest)
如果您有很多 cbxxx.txt
文件,也许另一种方法是使用 set
计算此列表与 os.listdir
结果的交集(以便更快地查找比一个 list
,如果有很多元素更有价值):
for f in {'cb10.txt','cb11.txt'}.intersection(os.listdir(".")):
shutil.move(f,dest)
在 Linux 上,有很多 "cb" 文件,这会更快,因为 listdir
不执行 fstat
,而 os.path.exists
编辑:如果文件具有相同的 prefix/suffix,您可以使用集理解构建查找集以避免乏味 copy/paste:
s = {'cb{}.txt'.format(i) for i in ('10','11')}
for f in s.intersection(os.listdir(".")):
或第一个选择:
for p in ['10','11']:
f = "cb{}.txt".format(p)
if os.path.exists(f):
shutil.move(f,dest)
编辑:如果必须移动所有 cb*.txt
个文件,那么您可以使用glob.glob("cb*.txt")
。我不会详细说明,链接的 "duplicate target" 答案解释得更好。
我有大量以 "cb" + 数字(如 cb10、cb13)组合命名的 .txt 文件,我需要从包含所有名为在 "cb + number" 中,包括目标文件。
目标文件名中的数字都是随机的,所以我必须列出所有文件名。
import fnmatch
import os
import shutil
os.chdir('/Users/college_board_selection')
os.getcwd()
source = '/Users/college_board_selection'
dest = '/Users/seperated_files'
files = os.listdir(source)
for f in os.listdir('.'):
names = ['cb10.txt','cb11.txt']
if names in f:
shutil.move(f,dest)
if names in f:
不会起作用,因为 f
是文件名,而不是列表。也许你想要 if f in names:
但是你不需要为此扫描整个目录,只需循环你的目标文件,如果它们存在:
for f in ['cb10.txt','cb11.txt']:
if os.path.exists(f):
shutil.move(f,dest)
如果您有很多 cbxxx.txt
文件,也许另一种方法是使用 set
计算此列表与 os.listdir
结果的交集(以便更快地查找比一个 list
,如果有很多元素更有价值):
for f in {'cb10.txt','cb11.txt'}.intersection(os.listdir(".")):
shutil.move(f,dest)
在 Linux 上,有很多 "cb" 文件,这会更快,因为 listdir
不执行 fstat
,而 os.path.exists
编辑:如果文件具有相同的 prefix/suffix,您可以使用集理解构建查找集以避免乏味 copy/paste:
s = {'cb{}.txt'.format(i) for i in ('10','11')}
for f in s.intersection(os.listdir(".")):
或第一个选择:
for p in ['10','11']:
f = "cb{}.txt".format(p)
if os.path.exists(f):
shutil.move(f,dest)
编辑:如果必须移动所有 cb*.txt
个文件,那么您可以使用glob.glob("cb*.txt")
。我不会详细说明,链接的 "duplicate target" 答案解释得更好。