首页 > 解决方案 > 将目录中的多个文件转换为 .txt 格式。但是文件名变成二进制

问题描述

所以我正在创建抄袭软件,为此,我需要将 .pdf、.docx、[在此处输入图像描述][1] 等文件转换为 .txt 格式。我成功地找到了一种将一个目录中的所有文件转换为另一个目录的方法。但问题是,这种方法正在改变文件名

文件名

成二进制值。我需要获取下一阶段需要的原始文件名。

在此处输入图像描述

**Code:**
import os
import uuid
import textract
source_directory = os.path.join(os.getcwd(), "C:/Users/syedm/Desktop/Study/FOUNDplag/Plagiarism-checker-Python/mainfolder")

for filename in os.listdir(source_directory):
    file, extension = os.path.splitext(filename)
    unique_filename = str(uuid.uuid4()) + extension
    os.rename(os.path.join(source_directory,  filename), os.path.join(source_directory, unique_filename))

training_directory = os.path.join(os.getcwd(), "C:/Users/syedm/Desktop/Study/FOUNDplag/Plagiarism-checker-Python/trainingdata")

for process_file in os.listdir(source_directory):
    file, extension = os.path.splitext(process_file)

    # We create a new text file name by concatenating the .txt extension to file UUID
    dest_file_path = file + '.txt'

    # extract text from the file
    content = textract.process(os.path.join(source_directory, process_file))

    # We create and open the new and we prepare to write the Binary Data which is represented by the wb - Write Binary
    write_text_file = open(os.path.join(training_directory, dest_file_path), "wb")

    # write the content and close the newly created file
    write_text_file.write(content)
    write_text_file.close()

标签: python-3.xdirectorynlpoperating-system

解决方案


删除重命名文件的这一行:

os.rename(os.path.join(source_directory,  filename), os.path.join(source_directory, unique_filename))

这也不是二进制的,而是一个uuid

干杯


推荐阅读