I am trying to do the following: An undetermined number of text files will be in a folder, I want to: 1. Open one file at a time and then 2. Read through the text in the file for a specific string and then 3. Append the whole contents of the text file to a docx file and save as the name of the string in step 2 4. Repeat for the following text files in the folder
I have completed all of this and thought i had it working. However, when the files are saved everything looks good but the first text file opened is then copied over to all of the other docx files that have now been created instead of each one being copied over and closed. What am I missing?
import docx
import os
design_doc = docx.Document("Configuration_V1.docx")
directory = r"C:\Configuration Files"
all_files = os.listdir(directory)
for config_file in all_files:
with open(os.path.join(directory, config_file), "r") as f:
config = f.read()
design_doc.add_paragraph(config)
target = "hostname"
words = config.split()
for i,w in enumerate(words):
if w == target:
hostname = words[i+1]
design_doc.save(hostname + ".docx")
f.close()
To clarify, the docx files are created with the proper names as the string in each text file will always be different and is being read, however when I open each new docx file, the text copied over is all from the first text file. Each text files contents should be appended to each docx.
Thank you
If you want a new document each time, you need to create a new one each time. Otherwise you are just adding a new paragraph to the same "in-memory" document and saving it as a new name.
I think you want something like this:
directory = r"C:\Configuration Files"
all_files = os.listdir(directory)
for config_file in all_files:
with open(os.path.join(directory, config_file), "r") as f:
config = f.read()
design_doc = docx.Document("Configuration_V1.docx")
design_doc.add_paragraph(config)
target = "hostname"
words = config.split()
for i, w in enumerate(words):
if w == target:
hostname = words[i+1]
design_doc.save(hostname + ".docx")
f.close()