xlrd python does not work - "syntax error" - python

I'm trying to get familiar with xlrd so I copied an example into my IDE (spyder). I'm using python(x,y) 2.7.6.1
This is my example
import xlrd
import os
filename=os.path.join("C:/","Desktop/myfile"):
book = xlrd.open_workbook(filename)
print "The number of worksheets is", book.nsheets
print "Worksheet name(s):", book.sheet_names()
sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
for rx in range(sh.nrows):
print sh.row(rx)
As you can see, I listened to advice on SE here but it still does not work (syntax error). As it is advised here I have written stuff in os.path.join() in manner given in the accepted answer.
This is error log:
runfile('C:/Users/PC/.spyder2/.temp.py', wdir=r'C:/Users/PC/.spyder2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Users/PC/.spyder2/.temp.py", line 12
filename=os.path.join("C:/","/Users/PC/Desktop/myfile"):
^
SyntaxError: invalid syntax
UPDATE
Now, when I removed colon from the end of the line with "join" i got another syntax error. This is it:
runfile('C:/Users/PC/.spyder2/.temp.py', wdir=r'C:/Users/PC/.spyder2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Users/PC/.spyder2/.temp.py", line 13, in <module>
book = xlrd.open_workbook(filename)
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 394, in open_workbook
f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: 'C:/Users/PC/Desktop/myfile'
What am I doing wrong? What should I do instead?

It's the colon at the end of the join line. It shouldn't be there.

The syntax error is that there should be no : at the end of the first line.
The "no such file or directory" error is because the desktop is not a directory located at "C:/Desktop". There's actually more than one directory whose contents show on the desktop, but probably what you want is "C:/Users/USERNAME/Desktop/", where USERNAME is of course your username on the machine.
If you want to access the home directory in general (i.e. not just yours, you want the home directory of whoever is running the script) then you can access the HOMEDRIVE and HOMEPATH environment variables.

As suggested by demented hedgehog and Steve Jessop i had to convert following line
filename=os.path.join("C:/","Desktop/myfile"):
into
filename=os.path.join("C:/","/Users/PC/Desktop/myfile.xls")
So I just had to remove colon, write correct directory and write myfile.xls instead of just myfile.

Related

I'm trying to pass a variable to another script as an argument but it isnt working

When I change the content file and styleFile vars for just the file path, it works fine. So I know that the content file is there and that it can find it.
I must be passing a variable incorrectly to the other python script. I've been trying but I can't google myself out of this one at the moment.
import os
listStyles = ['/content/neural-style-tf/styles/1.png']
listContent = ['/content/neural-style-tf/image_input/00078.png']
i = 0
for imageName in listStyles:
stylefile = imageName
contentfile = listContent[i]
i = i + 1
print (stylefile)
print (contentfile)
print ('')
!python neural_style.py --content_img contentfile --style_imgs stylefile
Output:
/content/neural-style-tf/styles/1.png
/content/neural-style-tf/image_input/00078.png
Traceback (most recent call last):
File "neural_style.py", line 889, in <module>
main()
File "neural_style.py", line 886, in main
else: render_single_image()
File "neural_style.py", line 849, in render_single_image
content_img = get_content_image(args.content_img)
File "neural_style.py", line 715, in get_content_image
check_image(img, path)
File "neural_style.py", line 552, in check_image
raise OSError(errno.ENOENT, "No such file", path)
FileNotFoundError: [Errno 2] No such file: './image_input/contentfile'
I'm just dumb and need to not just brute force a language when I need it and learn it beforehand.
If anyone else comes across this you need to put a $ in front of the variable to let python know you're passing a var instead of a string.

Python: KeyError: u'key' when analyzing multiple netCDF files

I'm relatively new to Python and am trying to analyze an entire folder of netCDF files. When I try to run my code I get the key error: u'satcode'. Here is my code:
import netCDF4 as nc
import glob
import numpy as np
filenames = []
for name in glob.glob("/Users/my_name/Desktop/ISCCP/*"):
print name
filenames.append(name)
# below reads multiple files (file_list)
f = nc.MFDataset(filenames)
I know the error is with f = nc.MFDataset(filenames), but I don't know why.
My traceback says:
runfile('/Users/my_name/.spyder/West_Coast_Model.py', wdir='/Users/my_name/.spyder')
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGG.v01r00.GLOBAL.1983.07.01.0000.GPC.10KM.CS00.EA1.00 (5).nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.0300.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.0600.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.0900.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.1200.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.1500.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.1800.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.07.99.2100.GPC.10KM.CS00.EA1.00.nc
/Users/my_name/Desktop/ISCCP/ISCCP-Basic.HGH.v01r00.GLOBAL.1983.08.99.0000.GPC.10KM.CS00.EA1.00.nc
Traceback (most recent call last):
File "", line 1, in
runfile('/Users/my_name/.spyder/West_Coast_Model.py', wdir='/Users/my_name/.spyder')
File "/Users/my_name/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "/Users/my_name/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/my_name/.spyder/West_Coast_Model.py", line 20, in
f = MFDataset(filenames)
File "netCDF4/_netCDF4.pyx", line 5888, in >netCDF4._netCDF4.MFDataset.init
KeyError: u'satcode'
I think I figured out the problem. The 0th term in the files was corrupted, so I redownloaded it and converted it into netCDF4_CLASSIC and it worked.

gensim file not found error

I am executing the following line:
id2word = gensim.corpora.Dictionary.load_from_text('wiki_en_wordids.txt')
This code is available at "https://radimrehurek.com/gensim/wiki.html". I downloaded the wikipedia corpus and generated the required files and wiki_en_wordids.txt is one of those files. This file is available in the following location:
~/gensim/results/wiki_en
So when i execute the code mentioned above I get the following error:
Traceback (most recent call last):
File "~\Python\Python36-32\temp.py", line 5, in <module>
id2word = gensim.corpora.Dictionary.load_from_text('wiki_en_wordids.txt')
File "~\Python\Python36-32\lib\site-packages\gensim\corpora\dictionary.py", line 344, in load_from_text
with utils.smart_open(fname) as f:
File "~\Python\Python36-32\lib\site-packages\smart_open\smart_open_lib.py", line 129, in smart_open
return file_smart_open(parsed_uri.uri_path, mode)
File "~\Python\Python36-32\lib\site-packages\smart_open\smart_open_lib.py", line 613, in file_smart_open
return open(fname, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'wiki_en_wordids.txt'
Even though the file is available in the required location I get that error. Should I place the file in any other location? How do I determine what the right location is?
The code requires an absolute path here. Relative path should be used when entire operation is carried out in the same directory location, but in this case, the file name is passed as argument to some other function which is located at different location.
One way to handle this situation is using abspath -
import os
id2word = gensim.corpora.Dictionary.load_from_text(os.path.abspath('wiki_en_wordids.txt'))

Winerror 3: File not found using ac2git

I was using the ac2git tool to concert my accurev depot to git repository.
I am getting the following error when running the command python ac2git.py after following the necessary steps, as instructed here.
2016-08-29 09:54:14,058 - ac2git - ERROR - The script has encountered an exception, aborting!
Traceback (most recent call last):
File "ac2git.py", line 3596, in AccuRev2GitMain
rv = state.Start(isRestart=args.restart, isSoftRestart=args.softRestart)
File "ac2git.py", line 2974, in Start
self.RetrieveStreams()
File "ac2git.py", line 1556, in RetrieveStreams
tr, commitHash = self.RetrieveStream(depot=depot, stream=streamInfo,dataRef=dataRef, stateRef=stateRef, hwmRef=hwmRef, startTransaction=self.config.accurev.startTransaction, endTransaction=endTr.id)
File "ac2git.py", line 1511, in RetrieveStream
dataTr, dataHash = self.RetrieveStreamData(stream=stream, dataRef=dataRef,stateRef=stateRef)
File "ac2git.py", line 1394, in RetrieveStreamData
commitHash = self.Commit(transaction=tr, allowEmptyCommit=True,messageOverride="transaction {trId}".format(trId=tr.id), parents=[], ref=dataRef)
File "ac2git.py", line 670, in Commit
self.PreserveEmptyDirs()
File "ac2git.py", line 440, in PreserveEmptyDirs
if git.GetGitDirPrefix(path) is None and len(os.listdir(path)) == 0:
FileNotFoundError: [WinError 3] The system cannot find the path specified:'C:///Users/*****/*****/app/node_modules/bower/node_modules/update-notifier/node_modules/latest-version/node_modules/package-json/node_modules/registry-url/node_modules/npmconf/node_modules/config-chain/node_modules/proto-list'
The error is quite vague and I can't seem to find any documentation on this tool that can help with the error. Has anyone faced this issue before?
I am not familiar with the tool you are using but it seems the last line in the output excerpt you provided gives the best information:
FileNotFoundError: [WinError 3] The system cannot find the path specified:'C:///Users/*****/*****/app/node_modules/bower/node_modules/update-notifier/node_modules/latest-version/node_modules/package-json/node_modules/registry-url/node_modules/npmconf/node_modules/config-chain/node_modules/proto-list'
That path looks to be malformed with extra slashes and directory names that are not valid within the file system. Also, the file path is at 227 characters in the output and if the directory names between "Users" and "app" are long enough, you could be hitting the 256 character path name limit in Windows.

File txt: FileNotFoundError: [Errno 2] No such file or directory

i have a txt file and if i try to open it python says:
runfile('/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python/untitled0.py', wdir='/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python')
Traceback (most recent call last):
File "<ipython-input-30-b4bdfdd17ca2>", line 1, in <module>
runfile('/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python/untitled0.py', wdir='/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python')
File "/Users/costanzanaldi/anaconda/lib/python3.4/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/Users/costanzanaldi/anaconda/lib/python3.4/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/Users/costanzanaldi/Desktop/tesi/Tesi_Naldi/COdice _Python/untitled0.py", line 13, in <module>
in_file = open("POLO_SCIENTIFICO_(LAMMA).txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'POLO_SCIENTIFICO_(LAMMA).txt'
1)the file EXISTS!
2)the path is correct! It is in the desktop!
You need to change your directory to your desktop in order to access the file. You'd do that using the os module, like this:
import os
os.chdir("/path/to/Desktop")
Presumably this means the file is not on the desktop. (I assume you changed Ethan's "/path/to/Desktop" to the correct path in your system, which is "/Users/costanzanaldi/Desktop"?). Wherever it is, you need to give open() the full path to POLO_SCIENTIFICO_(LAMMA).txt unless you have chdir'd to the correct directory. I assume you have got the letter-case correct in POLO_SCIENTIFICO_(LAMMA).txt :-)

Categories