I am trying to load an excel file within an IronPython script, which is embedded within a software.
I tried to do this with the following code:
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel
excel = Excel.ApplicationClass()
excel.Visible = True
workbook = excel.Workbooks.Open("C:\Users\antoi\Desktop\rimo_report\ae-project-reporting\codes_02_heat_recovery\data\unit_data_simp_08.xlsx")
However, I get an error that the file path cannot be found. From the error, it seems it is not searching within my own computer. How could one do this ? Do I have to import other packages ?
if it's just a path error, try to escape your \.
\ is a character used to escape some other characters (such as quotes, new lines, etc)
So when python is reading your code and interpreting it, it is trying to understand the characters you escaped such as \U, \a ...
To avoid this problem you can try this :
workbook = excel.Workbooks.Open("C:\\Users\\antoi\\Desktop\\rimo_report\\ae-project-reporting\\codes_02_heat_recovery\\data\\unit_data_simp_08.xlsx")
Related
I've been working on a program that reads out an specific PDF and converts the data to an Excel file. The program itself already works, but while trying to refine some aspects I ran into a problem. What happens is the modules I'm working with read directories with simple slashes dividing each folder, such as:
"C:/Users/UserX"
While windows directories are divided by backslashes, such as:
"C:\Users\UserX"
I thought using a simple replace would work just fine:
directory.replace("\" ,"/")
But whenever I try to run the program, the \ isn't identified as a string. Instead it pops up as orange in the IDE I'm working with (PyCharm). Is there anyway to remediate this? Or maybe another useful solution?
In general you should work with the os.path package here.
os.getcwd() gives you the current directory, you can add a subfolder of it via more arguments, and put the filename last.
import os
path_to_file = os.path.join(os.getcwd(), "childFolder", filename)
In Python, the '\' character is represented by '\\':
directory.replace("\\" ,"/")
Just try adding another backslash.
First of all you need to pass "C:\Users\UserX" as a raw string. Use
directory=r"C:\Users\UserX"
Secondly, suppress the backslash using a second backslash.
directory.replace("\\" ,"/")
All of this is required as in python the backslash (\) is a special character known as an escape character.
Try this:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath)
Output:<< C:/temp/myFolder/example/ >>
I'm trying to learn the basic of how the IBM Watson Personality Insights API works before it shuts down at the end of this year. I have a basic text file that I want analyzed, but I'm having trouble getting the code to run properly. I have been trying to follow along on the official sits instructions, but I'm stuck. What am I doing wrong? (I have blotted out my key in the below code).
from ibm_watson import PersonalityInsightsV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
authenticator = IAMAuthenticator('BlottedOutKey')
personality_insights = PersonalityInsightsV3(
version='2017-10-13',
authenticator=authenticator
)
personality_insights.set_service_url('https://api.us-west.personality-insights.watson.cloud.ibm.com')
with open(join(C:\Users\AWaywardShepherd\Documents\Data Science Projects\TwitterScraper-master\TwitterScraper-master\snscrape\python-wrapper\Folder\File.txt), './profile.json')) as profile_json:
profile = personality_insights.profile(
profile_json.read(),
content_type='text/plain',
consumption_preferences=True,
raw_scores=True)
.get_result()
print(json.dumps(profile, indent=2))
I keep getting the following nondescript syntax error:
File "<ipython-input-1-1c7761f3f3ea>", line 11
with open(join(C:\Users\AWaywardShepherd\Documents\Data Science Projects\TwitterScraper-master\TwitterScraper-master\snscrape\python-wrapper\Folder\File.txt), './profile.json')) as profile_json:
^ SyntaxError: invalid syntax
There is so much wrong with that open line.
join is expecting an itterable which it joins into a single string.
In Python, strings become strings by enclosing them with quotes (paths are just strings !)
You are only passing one value into join, which makes it redundant.
The second parameter for open should be a mode, and not a file name.
It looks like you are trying to append a directory with a file name, but for that to work the directory shouldn't end with a filename.
The brackets don't match - You have 2 opening brackets and 3 closing brackets.
In Python you use join to join strings to gather. Normally this would be a path and a filename. Getting the path from the current working directory and joining it with a path.
import os
file = os.path.join(os.getcwd(), 'profile.json')
In your code you are only passing in one string, so there is no need to use join.
Using open you pass in the filename and the mode. The mode would be something like 'r' indicating read mode. So the code with the join becomes.
import os
with open(os.path.join(os.getcwd(), 'profile.json'), 'r') as profile_json:
here is my simple code of python that I wrote to save the screenshot of a webpage.
from selenium import webdriver
import time
driver=webdriver.Firefox()
driver.get("https://www.google.co.in")
driver.implicitly_wait(2)
driver.save_screenshot("D\amanulla\test.png")
driver.quit()
Though, the program running without any errors, I do not see any screenshots saved on my machine. Can someone help me on this?
You are missing : from "D\amanulla\test.png" and you need to escape the \ as well, so effectively the line will be either:
"D:\\amanulla\\test.png"
or
"D:/amanulla/test.png"
I do not see any screenshots saved on my machine
Look for a file named Dmanulla est.png in the default Downloads location for your browser... because that is what you are instructing WebDriver to do with the line:
driver.save_screenshot("D\amanulla\test.png")
Explanation:
The string "D\amanulla\test.png" will be interpreted as "Dmanulla est.png". This is because backslashes are escape sequences within Python strings. Your directory separators will be interpreted as \a (bell) and \t (tab).
Also, the : separator is missing between the drive letter and the file path, so it is treating the entire string as a filename. In the absence of a directory name, it should save to browser's default "Downloads" directory.
Solution:
driver.save_screenshot(r"D:\amanulla\test.png")
This uses a raw string so the backslashes are not interpreted as escape sequences, and it adds the missing : as the drive letter separator.
I started to learn pandas by following this tutorial:
https://github.com/jvns/pandas-cookbook
Right in the first chapter I try very elementary example of reading a csv file. The example goes like this:
import pandas as pd
broken_df = pd.read_csv("..\data\bikes.csv")
I get a lengthy error message, which ends with a line:
FileNotFoundError: File b'..\\data\x08ikes.csv' does not exist
So although I write 'bikes.csv', which I have in the correct folder, the program seems to be searching for a file called 'x08ikes.csv'. Could this be an encoding error? sys.getdefaultencoding() returns 'utf-8'.
I am using Anaconda3 for 64bit Windows, version 4.4.0. My browser is Brave. Any ideas what is going wrong here?
The backslash character '\' has special meaning; it tries to "escape" the next character. In this case '\b' is an escape character that does have a meaning. There are three ways around this:
Escape the escapes:
You can use the backslash to escape the next backslash, telling Python "this is just another character"
broken_df = pd.read_csv("..\\data\\bikes.csv")
Use a raw string:
Placing r at the beginning of a string tells Python to interpret everything in the string as-is
broken_df = pd.read_csv(r"..\data\bikes.csv")
Use forward slashes:
This is specific to file paths. You can trace the directory to you file using forward slashes instead of backslashes.
broken_df = pd.read_csv("../data/bikes.csv")
What you can do is, upload the bikes.csv in to the Jupyter Home "Files" tab. Open it and you may still see the message. Then go to File->New, and you may get a new blank file. Open the original bikes.csv in notepad, copy and paste the content in to the file in jupyter notebook. This may help to resolve it.
Then you can run the following code.
import pandas as pd
broken_df = pd.read_csv("..\data\bikes.csv")
I was writing a python script which will take some data from sql server and then write to the current directory as excel. I am using pandas for it. And to get the current directory I am using package os
import os
def getCurrDir():
return os.getcwd().replace(" ","\ ")
now when calling this function while writing a excel sheet like this
writer = pandas.ExcelWriter(str(self.getCurrDir())+"/Temp_ID.xlsx", engine="xlsxwriter")
temp.to_excel(writer,"Temp_ID_Data", index=False)
writer.save()
I am not able to write because the error is
FileNotFoundError: [Errno 2] No such file or directory: '/home/srinath/Documents/Copy/Affine/workspace\\ python/Swipe/Temp_ID.xlsx'
One can see that the double slash is coming up. I thought that double slash is just for representation and I have learnt from this link . So what is going on?
I am using python 3.4 from continuum.
I am using centos 7 64 bit.
You don't need escape the spaces in Python.
Define getCurrDir() as
def getCurrDir():
return os.getcwd()
When you escape your spaces in Python with a backslash, Python then thinks your intended path has a backslash in it, and tries to handle the file access by adding another backslash to your backslash. Hence the invalid workspace\\ python file access attempt.
You can use os.path.join and os.getcwd to create correct path:
writer = pandas.ExcelWriter(os.path.join(os.getcwd(),"Temp_ID.xlsx"), engine="xlsxwriter")