Python word client cannot find .dotx - python

Python cannot currently find my file.
import os
import win32com.client
word=win32com.client.Dispatch("Word.Application")
word.Documents.Open('Test_template')
I am getting 'Sorry we can't find your file'.
When I run
import os
print(os.listdir('.'))
I can see 'Test_template.dotx'.
When I change
word.Documents.Open('Test_template')
to
word.Documents.Open('Test_template.dotx')
I get the same error

I don't see a directory specified here (although the fact that os.listdir() returns the item seems encouraging), but try specifying the full directory path, like this:
word.Documents.Open('//folder_1/folder_2/Test_template.dotx')
# You could also specify the working directory explicitly with os, as in:
os.chdir('//folder_1/folder_2')
And double-check that the filename matches exactly - I have definitely hit these errors with a single letter that was supposed to be lower vs. uppercase.

The issue ended up being a Citrix connection that masked the true file location. So the path appeared correct but was incorrect.

Related

Python searching for image in wrong directory

I am trying to load some assets onto my program that I have them in a folder called 'Graphics', which is inside the folder 'Snake', which is inside the folder 'Projects', which is inside the folder 'Python'. However, also inside that folder 'Python' is another folder named 'HelloWorld'.
I am trying to load some assets in a program that I am running in 'Snake' and Python is searching for the assets in the 'HelloWorld' folder (which is where I used to keep my python files).
I get the error:
FileNotFoundError: No file 'Projects/Snake/Graphics/apple.png' found in working directory 'C:\Users\35192\OneDrive - WC\Desktop\Python\HelloWorld'
I believe that for this I have to change the default directory for vs code. I have changed the default directory for the command prompt and it did nothing. Perhaps this is because the python that I am running in the command prompt is different from the one in vs code (?)
How do I fix this?
Thank you in advance.
Edit:
This is how I am currently loading the image:
apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()
Use pathlib to construct the path to your images. You wil have to add import pathlib to your code.
pathlib.Path(__file__) will give you the path to the current file. pathlib.Path(__file__).parent will give you the folder. Now you can construct the path with the / operator.
Try the following code and check the output.
import pathlib
print(pathlib.Path(__file__))
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'Grahics' / 'apple.png')
Now you will be able to move the full project to a totally different folder without having to adjust any code.
Your code example looks like this: apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()
If you import pathlib you can replace that with the dynamic approach:
path_to_image= pathlib.Path(__file__).parent / 'Grahics' / 'apple.png'
apple = pygame.image.load(path_to_image).convert_alpha()
I'm quite sure that pygame can work with a path from pathlib. If not then you have to convert the path to a string manually
apple = pygame.image.load(str(path_to_image)).convert_alpha()
You don't need to change the default directory. Just load from the full directory. That should look something like: "C:\Users\...\Python\Snake\Graphics\apple.png".
I think the simplest way is to first see your active directory by simply typing in
pwd, and then you could simply change the directory by cd("C:/path/to/location"), remember you have to use the backslash, or just use the following library:
import os
os.chdir("C:/path/to/location")
As pydragon posted, you could also import it by just giving the import function a path.

Os.path gives unexpected output

lately I started working with the Os module in python . And I finally arrived to this Os.path method . So here is my question . I ran this method in one of my kivy project just for testing and it actually didn't returned the correct output.The method consisted of finding if any directory exist and return a list of folders in the directory . otherwise print Invalid Path and return -1 . I passed in an existing directory and it returned -1 but the weird path is that when I run similar program out of my kivy project using the same path present in thesame folder as my python file it return the desired output .here is the image with the python file and the directory name image I have tested which returns invalid path.
and here is my code snippet
def get_imgs(self, img_path):
if not os.path.exists(img_path):
print("Invalid Path...")
return -1
else:
all_files = os.listdir(img_path)
imgs = []
for f in all_files:
if (
f.endswith(".png")
or f.endswith(".PNG")
or f.endswith(".jpg")
or f.endswith(".JPG")
or f.endswith(".jpeg")
or f.endswith(".JPEG")
):
imgs.append("/".join([img_path, f]))
return imgs
It's tough to tell without seeing the code with your function call. Whatever argument you're passing must not be a valid path. I use the os module regularly and have slowly learned a lot of useful methods. I always print out paths that I'm reading or where I'm writing before doing it in case anything unexpected happens, I can see that img_path variable, for example. Copy and paste the path in file explorer up to the directory and make sure that's all good.
Some other useful os.path methods you will find useful, based on your code:
os.join(<directory>, <file_name.ext>) is much more intuitive than imgs.append("/".join([img_path, f]))
os.getcwd() gets your working directory (which I print at the start of scripts in dev to quickly address issues before debugging). I typically use full paths to play it safe because Python pathing can cause differences/issues when running from cmd vs. PyCharm
os.path.basename(f) gives you the file, while os.path.dirname(f) gives you the directory.
It seems like a better approach to this is to use pathlib and glob. You can iterate over directories and use wild cards.
Look at these:
iterating over directories: How can I iterate over files in a given directory?
different file types: Python glob multiple filetypes
Then you don't even need to check whether os.path.exists(img_path) because this will read the files directly from your file system. There's also more wild cards in the glob library such as * for anything/any length, ? for any character, [0-9] for any number, found here: https://docs.python.org/3/library/glob.html

Renaming files with Chinese characters in Python

I'm trying to rename some files that have Chinese characters. However, the following won't work:
import os
for filename in os.listdir(r"C:\Users\mas\Desktop\"):
if filename.startswith("你好"):
os.rename(filename, filename[7:])
it gives the error " The system cannot find the file specified: '你好 Hello.txt"
Do I need to change some settings or something here?
Based on the error message, it seems the file is not found
I came across similar problem, and I solved it by changing current working directory first
In your case
# Change working directory first
os.chdir("C:\Users\mas\Desktop")
# then do the loop
for filename in os.listdir(r"C:\Users\mas\Desktop\"):
...

How to access file in parent directory using python?

I am trying to access a text file in the parent directory,
Eg : python script is in codeSrc & the text file is in mainFolder.
script path:
G:\mainFolder\codeSrc\fun.py
desired file path:
G:\mainFolder\foo.txt
I am currently using this syntax with python 2.7x,
import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
Although this works fine, is there a better (prettier :P) way to do this?
While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write
os.path.join( os.getcwd(), '..', 'foo.txt' )
...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.
To get a path to a file in the parent directory of the current script you can do:
import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')
You can try this
import environ
environ.Path() - 1 + 'foo.txt'
to get the parent dir the below code will help you:
import os
os.path.abspath(os.path.join('..', os.getcwd()))

pandas.read_csv FileNotFoundError: File b'\xe2\x80\xaa<etc>' despite correct path

I'm trying to load a .csv file using the pd.read_csv() function when I get an error despite the file path being correct and using raw strings.
import pandas as pd
df = pd.read_csv('‪C:\\Users\\user\\Desktop\\datafile.csv')
df = pd.read_csv(r'‪C:\Users\user\Desktop\datafile.csv')
df = pd.read_csv('C:/Users/user/Desktop/datafile.csv')
all gives the error below:
FileNotFoundError: File b'\xe2\x80\xaaC:/Users/user/Desktop/tutorial.csv' (or the relevant path) does not exist.
Only when i copy the file into the working directory will it load correct.
Is anyone aware of what might be causing the error?
I had previously loaded other datasets with full filepaths without any problems and I'm currently only encountering issues since I've re-installed my python (via Anaconda package installer).
Edit:
I've found the issue that was causing the problem.
When I was copying the filepath over from the file properties window, I unwittingly copied another character that seems invisible.
Assigning that copied string also gives an unicode error.
Deleting that invisible character made any of above code work.
Try this and see if it works. This is independent of the path you provide.
pd.read_csv(r'C:\Users\aiLab\Desktop\example.csv')
Here r is a special character and means raw string. So prefix it to your string literal.
https://www.journaldev.com/23598/python-raw-string:
Python raw string is created by prefixing a string literal with ‘r’
or ‘R’. Python raw string treats backslash () as a literal character.
This is useful when we want to have a string that contains backslash
and don’t want it to be treated as an escape character.
$10 says your file path is correct with respect to the location of the .py file, but incorrect with respect to the location from which you call python
For example, let's say script.py is located in ~/script/, and file.csv is located in ~/. Let's say script.py contains
import pandas
df = pandas.read_csv('../file.csv') # correct path from ~/script/ where script.py resides
If from ~/ you run python script/script.py, you will get the FileNotFound error. However, if from ~/script/ you run python script.py, it will work.
I know following is a silly mistake but it could be the problem with your file.
I've renamed the file manually from adfa123 to abc.csv. The extension of the file was hidden, after renaming, Actual File name became abc.csv.csv. I've then removed the extra .csv from the name and everything was fine.
Hope it could help anyone else.
import pandas as pd
path1 = 'C:\\Users\\Dell\\Desktop\\Data\\Train_SU63ISt.csv'
path2 = 'C:\\Users\\Dell\\Desktop\\Data\\Test_0qrQsBZ.csv'
df1 = pd.read_csv(path1)
df2 = pd.read_csv(path2)
print(df1)
print(df2)
On Windows systems you should try with os.path.normcase.
It normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes. Raise a TypeError if the type of path is not str or bytes (directly or indirectly through the os.PathLike interface).
import os
import pandas as pd
script_dir = os.getcwd()
file = 'example_file.csv'
data = pd.read_csv(os.path.normcase(os.path.join(script_dir, file)))
If you are using windows machine. Try checking the file extension.
There is a high possibility of file being saved as fileName.csv.txt instead of fileName.csv
You can check this by selecting File name extension checkbox under folder options (Please find screenshot)
below code worked for me:
import pandas as pd
df = pd.read_csv(r"C:\Users\vj_sr\Desktop\VJS\PyLearn\DataFiles\weather_data.csv");
If fileName.csv.txt, rename/correct it to fileName.csv
windows 10 screen shot
Hope it works,
Good Luck
Try using os.path.join to create the filepath:
import os
f_path = os.path.join(*['C:', 'Users', 'user', 'Desktop', 'datafile.csv'])
df = pd.read_csv(f_path)
I was trying to read the csv file from the folder that was in my 'c:\'drive but, it raises the error of escape,type error, unicode......as such but this code works
just take an variable then add r to read it.
rank = pd.read_csv (r'C:\Users\DELL\Desktop\datasets\iris.csv')
df=pd.DataFrame(rank)
There is an another problem on how to delete the characters that seem invisible.
My solution is copying the filepath from the file windows instead of the property windows.
That is no problem except that you should fulfill the filepath.
Experienced the same issue. Path was correct.
Changing the file name seems to solve the problem.
Old file name: Season 2017/2018 Premier League.csv
New file name: test.csv
Possibly the whitespaces or "/"
I had the same problem when running the file with the interactive functionality provided by Visual studio. Switched to running on the native command line and it worked for me.
For my particular issue, the failure to load the file correctly was due to an "invisible" character that was introduced when I copied the filepath from the security tab of the file properties in windows.
This character is e2 80 aa, the UTF-8 encoding of U+202A, the left-to-right embedding symbol. It can be easily removed by erasing (hitting backspace or delete) when you've located the character (leftmost char in the string).
Note: I chose to answer because the answers here do not answer my question and I believe a few folks (as seen in the comments) might meet the same situation as I did. There also seems to be new answers every now and then since I did not mark this question as resolved.
I had similar problem when I was using JupyterLab + Anaconda, and used my browser to type stuff on IDE.
My problem was simpler - there was a very subtle typo error. I didn't have to use raw text - either escaping or using {{r}} string worked for me :). If you use Anaconda with Jupyter Lab, I believe the Kernel starts with where you open the notebook from i.e. the working directory is that top level folder.
data = pd.read_csv('C:\\Users\username\Python\mydata.csv')
This worked for me. Note the double "\\" in "C:\\" where the rest of the folders use only a single "\".

Categories

Resources