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?
#1
hello, I have an error on the code below. Ths code converts all txt files into docx, from the same folder. But I have an error on path, I try many combinations, how to write the path, but still doesn't work.

This is the code:

# pip install docx
# pip install document
# pip install python-docx

from docx import Document
import re
import os

path = r'd:\2022_12_02'
direct = os.listdir(path)
print(path)

for i in direct:
    document = Document()
    document.add_heading(i, 0)
    myfile = open('d:\2022_12_02'+i).read()
    myfile = re.sub(r'[^\x00-\x7F]+|\x0c',' ', myfile) # remove all non-XML-compatible characters
    p = document.add_paragraph(myfile)
    document.save('d:\2022_12_02'+i+'.docx')
This is the error:

Error:
Traceback (most recent call last): File "D:\convert txt to docs.py", line 16, in <module> myfile = open('d:\2022_12_02'+i).read() FileNotFoundError: [Errno 2] No such file or directory: 'd:\x822_12_025g.txt' >>>
[Image: A5MjLh.jpg]

Can anyone test the code, and help me with a solution?
Reply
#2
Note that on line 16 (and also on line 19) you use normal string, not raw string like on line 9. Shouldn't you use path name in open(). Also You should use os.path.join() - right now you miss separator
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
I don't know Python very well.

can someone help me with a code modification that will solve the problem?
Reply
#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
#5
(Jan-29-2023, 12:37 PM)Melcu54 Wrote: I don't know Python very well.

can someone help me with a code modification that will solve the problem?

thanks, I run the code, doesn't give any error.

ok, But I cannot find the converted file. Where is the .doc or docx file? Shouldn't save it on the same folder, with the extension doc?
Reply
#6
no, no, I see now. It is working fine, except is doesn't change automaticaly the extension, I must change the extension myself.

So, your code is great. Thanks. But, for a better version, Python should make a new file with the new extension, and to read UTF-8 files.
Reply
#7
How can you do that, save the document to a different file? Where would that be done?
Reply
#8
yes, for example:

hitman.txt
love and devotion.txt
(alternative, Python can create automat a subfolder called docx)

those files will become:

hitman.docx
love and devotion.docx
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hi need help to make this code work correctly atulkul1985 5 701 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 440 Nov-07-2023, 04:32 PM
Last Post: snippsat
  newbie question - can't make code work tronic72 2 626 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Why wont this path work one way, but will the other way? cubangt 2 623 Sep-01-2023, 04:14 PM
Last Post: cubangt
  Something wrong with my code FabianPruitt 5 787 Jul-03-2023, 10:55 PM
Last Post: Pedroski55
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 870 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Code works but doesn't give the right results colin_dent 2 674 Jun-22-2023, 06:04 PM
Last Post: jefsummers
  Beginner: Code not work when longer list raiviscoding 2 765 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,469 Mar-27-2023, 07:38 AM
Last Post: buran
  Video recording with Raspberry Pi - What´s wrong with my python code? Montezuma1502 3 1,180 Feb-24-2023, 06:14 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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