Алгоритм Python, пропускающий поиск новых файлов, добавляемых в папку - PullRequest
0 голосов
/ 17 декабря 2018

Доброго времени суток всем, мой код на python ниже преобразует каждый файл doc, docx и rtf в .txt, что просто потрясающе.Когда я имел новый файл в каталоге, Ex. (Rootdir) в коде.Мой код находит файл и прекрасно его конвертирует.Однако, если я добавлю тот же самый файл в подкаталог rootdir, он не подберет новый добавляемый файл.Мой вопрос заключается в том, что я могу сделать по-другому в моем коде или вообще так, чтобы файлы, добавляемые в любой подкаталог или главный каталог (rootdir), были подобраны и преобразованы.

#RTF,DOCX,DOC TO TEXT
import win32com.client
import os
import re
import traceback
from os import listdir
from docx import Document
import shutil
import glob

rootdir = r'C:\Users\aac1928\Desktop\Test'
searchdir = rootdir + '\Search'
namedir = 'Search'
searchlist = []
dirlist = []
app = win32com.client.Dispatch('Word.Application')
app.Visible = False
app.DisplayAlerts = False

#Creates The search folder for text search in the directory
if os.path.exists(searchdir) == False:
    os.mkdir(searchdir)
    print((searchdir + " Has been created"))      
#Modifies all word doc file types to .TXT
    try:
        for root, dirs, files in os.walk(rootdir):
            for file in files:
                fullpath = os.path.join(*[root, file])
                if file.endswith(".docx"):
                    out_name = file.replace("docx", r"txt")
                    in_file = os.path.join(*[root, file])
                    out_file = os.path.abspath(root + "\\" + out_name)
                    doc = app.Documents.Open(in_file)
                    content = doc.Content.Text
                    print((file), out_file)
                    doc.SaveAs(out_file, FileFormat=7)
                    doc.Close()
                if file.endswith(".doc"):
                    out_name = file.replace("doc", r"txt")
                    in_file = os.path.join(*[root, file])
                    out_file = os.path.abspath(root + "\\" + out_name)
                    doc = app.Documents.Open(in_file)
                    content = doc.Content.Text
                    print((file), out_file)
                    doc.SaveAs(out_file, FileFormat=7)
                    doc.Close()
                if file.endswith(".rtf"):
                    out_name = file.replace("rtf", r"txt")
                    in_file = os.path.join(*[root, file])
                    out_file = os.path.abspath(root + "\\" + out_name)
                    doc = app.Documents.Open(in_file)
                    content = doc.Content.Text
                    print((file), out_file)
                    doc.SaveAs(out_file, FileFormat=7)

    except:
        pass


if os.path.exists(searchdir) == True:
    print('Search file is Present')
    for root, dirs, files in os.walk(searchdir, onerror=None):
        for filename in files:
            searchlist.append(os.path.splitext(filename)[0])

    try:
        for root, dirs, files in os.walk(rootdir):
            if namedir in dirs:
                dirs.remove(namedir)
                for filename in files:
                    if (os.path.splitext(filename)[0]) not in searchlist:
                        print(filename)
                        #for filename in filenames:
                        fullpath = os.path.join(*[root, filename])
                        if filename.endswith(".docx"):
                            out_name = filename.replace("docx", r"txt")
                            in_filename = os.path.join(*[root, filename])
                            out_filename = os.path.abspath(root + "\\" + out_name)
                            doc = app.Documents.Open(in_filename)
                            content = doc.Content.Text
                            print((filename), out_filename)
                            doc.SaveAs(out_filename, FileFormat=7)
                            doc.Close()
                        if filename.endswith(".doc"):
                            out_name = filename.replace("doc", r"txt")
                            in_filename = os.path.join(*[root, filename])
                            out_filename = os.path.abspath(root + "\\" + out_name)
                            doc = app.Documents.Open(in_filename)
                            content = doc.Content.Text
                            print((filename), out_filename)
                            doc.SaveAs(out_filename, FileFormat=7)
                            doc.Close()
                        if filename.endswith(".rtf"):
                            out_name = filename.replace("rtf", r"txt")
                            in_filename = os.path.join(*[root, filename])
                            out_filename = os.path.abspath(root + "\\" + out_name)
                            doc = app.Documents.Open(in_filename)
                            content = doc.Content.Text
                            print((filename), out_filename)
                            doc.SaveAs(out_filename, FileFormat=7)
                            doc.Close()
    except:
        pass

else:
    print("")

app.Quit()


#Moves the Converted Txt Files to The Search Folder 
try:
    for root, dirs, files in os.walk(rootdir):
        for file in files:
            for filename in file: 
                if namedir in dirs:
                    dirs.remove(namedir)
                if file.endswith('.txt'):
                    shutil.move(os.path.join(root, file), os.path.join(searchdir, file))
                break
except (IOError, OSError):  # ignore read and permission errors
            pass

1 Ответ

0 голосов
/ 17 декабря 2018

вот решение

import os
import shutil 

def absoluteFilePaths(directory):
   for dirpath,_,filenames in os.walk(directory):
       for f in filenames:
           yield os.path.abspath(os.path.join(dirpath, f))

rootdir = r'C:\Users\aac1928\Desktop\Test' 
file_names = list(absoluteFilePaths(rootdir))    
extensions = ['doc', 'docs', 'rtf']

for i in file_names:
    file_name, extension = i.split('.')
    if extension in extensions ans os.path.exists(i):
        new_file_name = file_name+ '.txt'
        shutill.move(i, new_file_name)
...