簡體   English   中英

如果文本文件中的行引用了不存在的文件,則將其刪除

[英]Delete lines of text file if they reference a nonexistent file

我有一個包含.jpg名稱列表的文本文件( images1.txt ),我還有一個包含.jpg圖像的文件夾( Bones )。 所有圖像名稱正好是42個字符(包括文件擴展名),並且每個字符都在包含該名稱和有關圖像的某些信息的單獨行中。 例如:

OO75768249870G_2018051_4A284DQ0-011628.jpg,1A4502432KJL459265,emergency
OO75768249870G_2018051_4A284DQ0-011629.jpg,1A451743245122,appointment

.jpg之后的所有內容都是我對照片的個人注釋。 Bones包含images1中命名的images1多個圖像中的許多,但不是全部。 使用命令提示符或python,如何從images1刪除與Bones文件夾中不存在的圖像相對應的行?

謝謝!

在python中:

import os

LEN_OF_FILENAME = 42

with open('images1.txt', 'r') as image_file:
    with open('filtered_images1.txt', 'w') as filtered_image_file:
        for line in image_file:
            image_name = line[:LEN_OF_FILENAME]
            path_to_image = os.path.join('Bones', image_name)
            if os.path.exists(path_to_image):
                filtered_image_file.write(line)

假設images1.txtBones在同一個文件夾中,如果在該文件夾中運行上述Python腳本,您將得到filtered_images1.txt 它僅包含在Bones中具有相應圖像的行。

這段代碼將從image1.txt中讀取各行,並使用骨骼目錄中文件所在的行創建一個image2.txt。

@ECHO OFF
IF EXIST image2.txt (DEL image2.txt)
FOR /F "tokens=1,* delims=," %%f IN ('TYPE "image1.txt"') DO (
    IF EXIST "bones\%%~f" (ECHO %%f,%%g >>"image2.txt")
)
EXIT /B

我認為最簡單的方法是使用findstr命令

rem /* Search for lines in file `images1.txt` in a case-insensitive manner that literally begin
rem    with a file name found in the directory `Bones` which in turn matches the naming pattern;
rem    then write all matching lines into a temporary file: */
dir /B /A:-D "Bones\??????????????_???????_????????-??????.jpg" | findstr /LIBG:/ "images1.txt" > "images1.tmp"
rem // Overwrite original `images1.txt` file by the temporary file:
move /Y "images1.tmp" "images1.txt" > nul

暫無
暫無

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

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