Python:如果文件名在列表中

0 投票
2 回答
9855 浏览
提问于 2025-04-18 06:48

我正在尝试弄清楚如何遍历一个文件夹,并移动那些在列表中的文件。我已经有了一个脚本,可以创建文件名的列表,所以现在我需要能够检查文件夹中的文件,如果它们在列表里,就把它们移动。

    import os, shutil
fileList = []
for root, dirs, files in os.walk(r'K:\Users\User1\Desktop\Python\New folder'):
    for file in files:
        if file.endswith('.txt'):
            fileList.append(file)
print fileList
source = "K:\\Users\\User1\\Desktop\\Python\\New folder"
destination = "K:\\Users\\User1\\Desktop\\Python\\New folder (2)"
for root, dirs, files in os.walk(r'K:\Users\User1\Desktop\Python\New folder'):
    for file in files:
        if fname in fileList:
            shutil.move(source, destination)

我使用了网上找到的其他代码片段来创建这个列表,但我还没搞明白如何把文件名当作一个变量来检查它是否在列表中。任何帮助都非常感谢。

2 个回答

0

如果我理解你的问题没错的话,你是想把一个文件夹里的所有文本文件移动到另一个文件夹吗?还是说你想在命令行里输入一个文件名,如果这个文件名在文件列表里,就把它移动到那个文件夹?

如果是第一种情况,你可以把代码简化成:

import os, shutil

source = r"K:\\Users\\User1\\Desktop\\Python\\New folder"
destination = r"K:\\Users\\User1\\Desktop\\Python\\New folder (2)"

for root, dirs, files in os.walk(source):
    for file in files:
        if file.endswith('.txt'):
            shutil.move(os.path.join(root,file), destination)

这样就可以把源文件夹里找到的所有文本文件移动到目标文件夹了。这样就不需要再保留一个中间列表了。

不过如果你想要第二种情况,也就是通过命令行传入一个参数,那么你可以把上面代码的最后两行改成:

if file == sys.argv[1]:
    shutil.move(os.path.join(root,file), destination)

记得要先 import syssys.argv 是一个数组,里面包含了你在调用这个 Python 脚本时使用的命令行参数。第一个元素是脚本的名字,第二个元素是第一个参数,你可以把它当作变量在你的脚本里使用。

0

选择合适的工具来完成任务:

from glob import glob
import shutil
import os

# source = "K:/Users/User1/Desktop/Python/New folder"
# destination = "K:/Users/User1/Desktop/Python/New folder (2)"
source = "."
destination = "dest"

txt_files = glob(os.path.join(source, "*.txt"))
print txt_files

for fname in txt_files:
    if not os.path.isfile(fname):
        continue
    print "moving '{f}' to '{d}'".format(f=fname, d=destination)
    shutil.move(fname, destination)

如果你在路径中不使用反斜杠,会让你的生活更轻松。Python对Windows这种奇怪的情况处理得还不错……

编辑 这里有一个可以递归工作的版本:

import os
import shutil
import fnmatch

# source = "K:/Users/User1/Desktop/Python/New folder"
# destination = "K:/Users/User1/Desktop/Python/New folder (2)"
source = "."
destination = "dest"

for root, dirs, files, in os.walk(source):
    for fname in fnmatch.filter(files, "*.txt"):
        src_path = os.path.join(root, fname)
        des_path = os.path.join(destination, fname)
        if os.path.exists(des_path):
            print "there was a name collision!"
            # handle it
        print "moving '{f}' to '{d}'".format(
            f=src_path, d=destination)
        shutil.move(fname, destination)

撰写回答