Python Forum
Why doesn't this code work? What is wrong with path?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why doesn't this code work? What is wrong with path?
#4
Code is not tested. Maybe it works directly, or you have to correct some errors.
Use pathlib.Path.
Don't run this code on Data you don't have a backup of.

import re
from pathlib import Path

from docx import Document

path = Path(r"d:\2022_12_02")

if path.exists():
    print(path, "exists")
else:
    print(path, "does not exist")
    raise SystemExit(-1)


for file in path.glob("*"):
    # file is a Path object

    document = Document()
    # file.name is the name of the file as str without the Path
    document.add_heading(file.name, 0)

    # Path objects do have the read_text, read_bytes
    # method and also supports
    # open with context managers

    # remove all non-XML-compatible characters
    file_content = re.sub(r"[^\x00-\x7F]+|\x0c", " ", file.read_text())
    document.add_paragraph(file_content)
    # if Document could not handle Path objects,
    # you must convert the Path object to a str

    # document.save(str(file))
    document.save(file)
Melcu54 likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Why doesn't this code work? What is wrong with path? - by DeaD_EyE - Jan-29-2023, 02:01 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extending list doesn't work as expected mmhmjanssen 2 238 May-09-2024, 05:39 PM
Last Post: Pedroski55
  hi need help to make this code work correctly atulkul1985 5 884 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 538 Nov-07-2023, 04:32 PM
Last Post: snippsat
  newbie question - can't make code work tronic72 2 742 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Why wont this path work one way, but will the other way? cubangt 2 705 Sep-01-2023, 04:14 PM
Last Post: cubangt
  Something wrong with my code FabianPruitt 5 916 Jul-03-2023, 10:55 PM
Last Post: Pedroski55
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 1,010 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Code works but doesn't give the right results colin_dent 2 774 Jun-22-2023, 06:04 PM
Last Post: jefsummers
  Beginner: Code not work when longer list raiviscoding 2 885 May-19-2023, 11:19 AM
Last Post: deanhystad
  Compiles Python code with no error but giving out no output - what's wrong with it? pythonflea 6 1,662 Mar-27-2023, 07:38 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020