簡體   English   中英

Python:列表中的IF文件名

[英]Python: IF filename in list

我試圖弄清楚如何瀏覽文件夾並移動列表中的文件。 我有創建文件名列表的腳本,所以現在我需要能夠將文件放在文件夾中,並在列表中移動它們。

    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)

我已經使用網上找到的其他片段來創建列表,但是我還無法理解如何將文件名作為變量來檢查它是否在列表中。 任何幫助深表感謝。

使用正確的工具進行工作:

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)

如果我正確理解了您的問題,您想將一個文件夾中的所有文本文件移動到另一個文件夾嗎? 還是要在命令行上傳遞文件名,如果文件名在fileList中,然后將其移至該文件夾?

在前一種情況下,您可以將代碼減少為:

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 sys sys.argv是一個數組,其中包含調用python腳本時使用的命令行參數。 元素0只是腳本的名稱,元素1是第一個參數,您可以將其用作腳本中的變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM