Search code examples
pythonpython-docx

Import "docx" could not be resolved error in Python project in Visual Studio


I am new to python and I tried to use docx module to automate some basic stuff.

I have installed python:

enter image description here

I have installed pip:

enter image description here

I have installed docx module using command:

pip install python-docx

instead of:

pip install docx

because I read that it install legacy version of that module.

Proof that I have docx installed:

enter image description here

Proof that I don't have legacy version istalled:

enter image description here

And even so when I code using Visual Studio it shows me:

enter image description here

And when I debug it shows me:

enter image description here

My full code is below but I don't think it is helpful in any way. What can I do to run it? Thank you in advance.

import os
from docx import Documents

# Set the directories
src_dir = "documents"
dst_dir = "output"

# Iterate through the files in the source directory
for file in os.listdir(src_dir):

# Check if the file is a .docx file
if file.endswith(".docx"):
    
    # Open the .docx file using the Document class from the docx module
    doc = Document(os.path.join(src_dir, file))
    
    # Iterate through the tables in the document
    for table in doc.tables:
        
        # Create a new .docx file in the output directory
        new_doc = Document()
        
        # Add the table to the new document
        new_doc.add_table(table)
        
        # Save the new document to the output directory
        new_doc.save(os.path.join(dst_dir, file))
    
    # Break out of the loop after the first .docx file is found
    break

Solution

  • Make sure that the python version you use for building the script is the same as the python version you use to run pip install docx or python-docx.

    When you run pip install ... it will show the part to the python version which is being installed, use it to compare with the python version which show when you build/debug the script.

    Example of logging when installing a library (it has python310 -> it is being installed on Python 3.10)

    Requirement already satisfied: loguru in c:\users\ntgr\appdata\roaming\python\python310\site-packages (0.6.0)
    

    Example of logging when running a script (it has Python310 -> it is running on Python 3.10):

    PS D:\_PROJECT\bot_hunter_5.0\hunter-5-0-bot>  & 'C:\Python310\python.exe' 'c:\Users\NTGR\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugp
    y\launcher' '56421' '--' 'd:\_PROJECT\bot_hunter_5.0\hunter-5-0-bot\bot.py
    

    In case the versions are mismatched, you can change the build/run python version by clicking the version which is located at the bottom-right in the VSCode (as in the image below)

    enter image description here

    Or specifying the python version when using pip install.