Python在写入之前检查文件是否存在

时间:2018-02-11 16:50:12

标签: python

我有一个包含.odt文件的文件,我想将它们转换为pdf。我的当前函数运行正常,问题是即使文件已经转换,该函数也会再次转换它,如果文件已经转换,我不想转换它。

有没有办法检查name.odt和name.pdf文件是否已经存在?

import sys
import os
import comtypes.client
import glob

def convert():
    for file in glob.glob("*.odt"): # Listing all files
        wdFormatPDF = 17
        in_file = os.path.abspath(file)
        name, ext = os.path.splitext(file)
        suffix = '.pdf'
        os.path.join(name + suffix)
        if not os.path.exists(name): # Pdf file doesn't exist 
            out_file = os.path.abspath(name)

            word = comtypes.client.CreateObject('Word.Application')
            doc = word.Documents.Open(in_file)
            doc.SaveAs(out_file, FileFormat=wdFormatPDF)
            print('the file ' + name +' has been converted')
        else :
            print('all the file are converted')

    doc.Close()
    word.Quit()

1 个答案:

答案 0 :(得分:0)

您的代码有一些不正确的事情。这是我为使其发挥作用所做的最小修改:

import sys
import os
import win32com.client
import glob

def convert():
    word = win32com.client.Dispatch('Word.Application')
    for input_file in glob.glob("*.odt"): # Listing all files
        wdFormatPDF = 17
        in_file = os.path.abspath(input_file)
        name, ext = os.path.splitext(input_file)
        suffix = '.pdf'
        name = name + suffix
        if not os.path.exists(name): # Pdf file doesn't exist 
            out_file = os.path.abspath(name)

            doc = word.Documents.Open(in_file)
            doc.SaveAs(out_file, FileFormat=wdFormatPDF)

            print('the file ' + name +' has been converted')

            doc.Close()

        else:
            print('The file ' + name + ' already exists')

    print('all the file are converted')
    word.Quit()

os.chdir(r"C:\Users\evensf\Documents\Question-48733924\Source")
convert()

以下是我对修改的评论:

  • 出于某种原因,我无法理解,我无法安装comtypes模块。所以我使用了Python for Win32 (pywin32) extensions附带的win32com模块。我认为它非常相似。
  • 我在循环外部打开了Word连接器对象。每次要打开文档时,您都不需要打开和关闭它。我没有这样做就无法使你的代码工作,它应该加快执行速度。
  • 我将您的变量名称从file更改为input_file,因为有一次该名称已经分配给something in Python,如果我没记错的话可能会造成灾难。我认为现在这并不相关,但为变量设置描述性名称总是一个好习惯。
  • 当您找到已存在的PDF文件时,您的代码似乎打印all the file are converted。我无法理解你为什么要那样做。因此,我已经在创建PDF文件时发出消息,并将消息放在循环之外。
  • 因为您似乎正在使用本地目录中的文件。我添加了一个命令来更改工作目录。

但我们可以进一步简化您的代码:

import win32com.client
import pathlib

source_directory = pathlib.Path(r"C:\Users\evensf\Documents\Question-48733924\Source")
wdFormatPDF = 17
destination_suffix = '.pdf'

word_application = win32com.client.Dispatch('Word.Application')
for current_file in source_directory.glob("*.odt"): # Listing all files
    absolute_current_file = current_file.resolve()
    destination_name = absolute_current_file.with_suffix(destination_suffix)
    if destination_name.exists(): 
        print('The file', destination_name, 'already exists. Not converting.')
    else:
        current_document = word_application.Documents.Open(str(absolute_current_file))
        current_document.SaveAs(str(destination_name), FileFormat=wdFormatPDF)

        print('A file has been converted to', destination_name)

        current_document.Close()

print('Finished converting files')
word_application.Quit()
  • 我使用了pathlib模块,它有很多条款来简化您的代码