Python shutil文件在os walk for循环中移动

时间:2016-10-06 18:28:16

标签: python-2.7 for-loop shutil

下面的代码在目录中搜索任何PDF,并且对于每个PDF,它会移动到附加了“_folder”的相应文件夹中。 它可以用更简单的术语表达吗?这实际上是不可读的。此外,如果找不到该文件夹​​,它会破坏PDF!

require "rails_helper"

RSpec.describe "Widget management", :type => :request do

  it "creates a Widget" do
    headers = {
      "ACCEPT" => "application/json",     # This is what Rails 4 accepts
      "HTTP_ACCEPT" => "application/json" # This is what Rails 3 accepts
    }
    post "/widgets", { :widget => {:name => "My Widget"} }, headers

    expect(response.content_type).to eq("application/json")
    expect(response).to have_http_status(:created)
  end

end

我真的想在构造变量name_of_file后遍历同一个目录,如果该变量在文件夹名称中,它会执行移动。然而,我遇到了试图嵌套另一个for循环的问题......

2 个答案:

答案 0 :(得分:0)

我会尝试这样的事情:

for root, dirs, files in os.walk(folder_path_variable):
    for filename in files:
        if filename.endswith('.pdf') and not filename.startswith('.'):
            filepath = os.path.join(root, filename)
            filename_prefix = filename.split('-')[0]
            dest_dir = os.path.join(root, filename_prefix + '_folder')
            if not os.path.isdir(dest_dir):
                os.mkdir(dest_dir)
            os.rename(filepath, os.path.join(dest_dir, filename))

答案 1 :(得分:0)

John Zwinck的回答是正确的,除了它包含一个错误,如果目标文件夹已经存在,则创建该文件夹中的文件夹并将pdf移动到该位置。我已经通过在内部for循环中添加'break'语句来修复此问题(对于文件中的文件名)。

以下代码现在可以正确执行。查找名为pdf的前几个字符的文件夹(将前缀拆分为' - '),尾部带有'_folder',如果存在则将pdf移入其中。如果没有,则使用前缀名称和'_folder'创建一个,并将pdf移入其中。

for root, dirs, files in os.walk(folder_path_variable):
    for filename in files:
        if filename.endswith('.pdf') and not filename.startswith('.'):
            filepath = os.path.join(root, filename)
            filename_prefix = filename.split('-')[0]
            dest_dir = os.path.join(root, filename_prefix + '_folder')
            if not os.path.isdir(dest_dir):
                os.mkdir(dest_dir)
            os.rename(filepath, os.path.join(dest_dir, filename))
    break