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:
Related
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")
I am trying to read a txt file(kept in another location) in python, but getting error.
FileNotFoundError
in ()
----> 1 employeeFile=open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt","r")
2 print(employeeFile.read())
3 employeeFile.close()
FileNotFoundError: [Errno 2] No such file or
directory:'C:\u202a/Users/xxxxxxxx/Desktop/python/files/employee.txt'
Code used:
employeeFile=open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt","r")
print(employeeFile.read())
employeeFile.close()
I tried using frontslash(/) and backslash(). But getting the same error.Please let me know what is missing in code.
I'm guessing you copy and pasted from a Windows property pane, switching backslashes to forward slashes manually. Problem is, the properties dialog shoves a Unicode LEFT-TO-RIGHT EMBEDDING character into the path so the display is consistent, even in locales with right-to-left languages (e.g. Arabic, Hebrew).
You can read more about this on Raymond Chen's blog, The Old New Thing. The solution is to delete that invisible character from your path string. Selecting everything from the initial " to the first forward slash, deleting it, then retyping "C:/, should do the trick.
As your error message suggests, there's a weird character between the colon and the forward slash (C:[some character]/). Other than that the code is fine.
employeeFile = open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt", "r")
You can copy paste this code and use it.
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")
I'm new to Python and i'd like to build a script (Python 3) to test electronic modules and save log files.
I'd like to save the logfiles in the following format:
201410log.txt (yearmonthlog.txt)
This is done with the code:
import os
logfile=open(time.strftime('%Y%mlog.txt'), 'a')
logfile.write('This is a test\n\n\n')
This way, every month a new log file is created.
However, i'd like the logfiles to be in in a subdirectory (\logs).
I tried approaches like
logfile=open(time.strftime('\logs\%Y%mlog.txt'), 'a')
and similar things but i couldnt get any of them to work.
I searched trough other questions on stackoverflow (for example: Relative paths in Python ) and elsewhere in the internet, but i couldnt find the right solution.
Could someone point me in the right direction?
(sorry for any mistakes/spelling errors, i'm no native english speaker)
Remove the leading backslash. It makes the path absolute. Beside that, you need to escape a backslash.
logfile = open(time.strftime('logs\\%Y%mlog.txt'), 'a')
or use r'raw string literal':
logfile = open(time.strftime(r'logs\%Y%mlog.txt'), 'a')
For your current path string literal, it does not make problem. But paths like 'a\nb' will not work because \n is interpreted as newline instead of a literal backslash and n.