Python, PyFITS, cannot open file - python

I have problem in opening FITS file in Python. I get following error-message:
File "G:\Anaconda\lib\site-packages\pyfits\file.py", line 416, in _open_filelike % self.mode)
IOError: File-like object does not have a 'write' method, required for mode 'ostream'
at hdulist = pft.open(path) line (I did import pyfits as pft).
I checked the path twice - it's correct.
I'm not able to find any reference to this error in context of using PyFITS and I will be gratefull for any help.
UPDATE:
I missed some details and I'm sorry for it.
First of all: I'm using PyFITS 3.3 under Anaconda distribution for Windows (Windows XP 32-bit).
Code of whole widget you can find at this link:
FileView
In a short - I'm making simple explorer for filesystem, just to let user navigate to folder with FITS files and read it from folder. All project is under PyQT4.

Obviously your path is not a subclass of basestring (I suppose you use Python 2.7) as it is expected by PyFITS. In fact path is a QString instance and you have to convert to unicode first.
So replace your line
hdulist = pft.open(path)
with
hdulist = pft.open(unicode(path.toUtf8(), encoding="UTF-8"))

Related

AttributeError pywin32

I use the pywin32 library since one week to parse visio files to extract shapes and their content. I ran my scripts several times but since yesterday when I execute them I have this error :
File "C:\Program Files\Python39\lib\site-packages\win32com\client\__init__.py", line 580, in __getattr__ raise AttributeError( AttributeError: '<win32com.gen_py.Microsoft Visio 16.0 Type Library.IVDocument instance at 0x1943434388768>' object has no attribute 'pages'
Here is the part of my script which generate the error :
import glob
import os
import win32com.client as w32
path = r"C\Users\..."
all_files = glob.glob(path + "/*.vsd")
visio = w32.Dispatch("visio.Application")
for filename in all_files:
print(filename)
vdoc = visio.Documents.Open(filename)
page = vdoc.pages(1) <-- the problematic line
shps = page.Shapes
I make a list of visio files and after I open them in the for loop I read the first page (they have all one page). The first visio open as well but after I have the error.
I tried to uninstall et reinstall pywin32, I worked in another repertory, change my import name... I tried on another PC and pywin works as well.
I really don't understand why python rise this error now, above all I don't touch this line .
Have you some ideas to resolve this problem ?
I don't understand how it works but capitalizing all commands like .Pages/.Type/.Text/.Shapes/.Names because before the commands uncapitatlized .pages/.type/.text/.shapes/.names worked... It's very weird if somebody have an explanation I take it.

Pytesseract Failed loading language 'chi-sim'

I am working on python tesseract package with sample code like the follows:
import pytesseract
from PIL import Image
tessdata_dir_config = "--tessdata-dir \"/opt/homebrew/Cellar/tesseract-lang/4.1.0/share/tessdata/\""
image = Image.open("dataset/test.jpeg")
text = pytesseract.image_to_string(image, lang = "chi-sim", config = tessdata_dir_config)
print(text)
And I received the following error message:
pytesseract.pytesseract.TesseractError: (1, 'Error opening data file /opt/homebrew/Cellar/tesseract-lang/4.1.0/share/tessdata/chi-sim.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory. Failed loading language 'chi-sim' Tesseract couldn't load any languages! Could not initialize tesseract.')
From my understanding, the error occurred when reading the file chi-sim.traineddata (which stands for Simplified Chinese), as I will explain the attempts I have made to settle this problem below.
My developing environment is M1 macOS, and I installed tesseract and tesseract-lang from Homebrew. I am pretty sure that the path specified above is exactly where the source files are located, since when I call
print(pytesseract.get_languages(config = ""))
I get a long list of languages printed, including chi-sim.
Further, if we just use English instead of Chinese, the following code can successfully recognize the English texts in an image:
text = pytesseract.image_to_string(image)
I've tried to specify environment variable TESSDATA_PREFIX in multiple ways, including:
Using config parameter as in the original code.
Adding global environment variable in PyCharm.
Adding the following line in the code
os.environ["TESSDATA_PREFIX"] = "tesseract/4.1.1/share/tessdata/"
Adding the following line to bash_profile in terminal
export TESSDATA_PREFIX=/opt/homebrew/Cellar/tesseract-lang/4.1.0/share/tessdata/
But unfortunately, none of these works.
It seems as if my file chi-sim.traineddata is, somehow, broken, so I directly downloaded the trained data file from GitHub (https://github.com/tesseract-ocr/tessdata/blob/master/chi_sim.traineddata), hit the "Download" button on the right, and placed the downloaded file in the tesseract-lang and original tesseract directory (where eng.traineddata is located). Yes, I've tried both, but neither works.
With respect to this issue, is there any potential solutions?
Code works for me on Linux if I use lang="chi_sim" with _ instead of - because file downloaded from server has name chi_sim.traineddata also with _ instead of -.
If I rename file into chi-sim.traineddata then I can use lang="chi-sim" (with - instead of _)

h5py.File(path) doesn't recognize folder path

I am in my project folder call "project". I have two neural network h5 file, one in "project/my_folder/my_model_1.h5", I also copy it to folder "project/my_model_2.h5". So I open my Jupyter Notebook which is working at "project" folder.
import h5py
f = h5py.File("my_model_2.h5") # has NO Issue
but
f = h5py.File("my_folder/my_model_1.h5") # OSError
It says OSError: Unable to open file (unable to open file: name = 'my_folder/my_model_1.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
Interestingly, I only have this issue when I do the same thing on my Mac, but I don't encounter any issue in Linux machine.
Please let me know if you know how to fix this. Thank you in advance.
So it looks like some hidden invalid character incidentally got copied when I simply copy and paste the file path from Mac folder system. Take a look at the code in the screen.
The Line 92 is the path name I directly copy and paste from Mac folder.
The Line 93 is the path I literally type with every single letter, then there is no error and .h5 file is loaded properly. It's a kinda of similar issue that has been spotted by someone at this link: Invalid character in identifier
I simply copy the error code to Pycharm, and the unwelcome character got busted.
So solution, for Mac user, be careful of of just simply copying the text from folder system, if something obviously weird, try type every letter into the text editor.
Specifying the absolute path using the os worked in windows
file_name = os.path.dirname(__file__) +'\\my_folder\\my_model_1.h5'
f = h5py.File(file_name)
dont forget to import os though

How to pass all files (with given name patterns) to python program in PyCharm using the parameters field in run/debug configurations?

I have a bunch of .html files in a directory that I am reading into a python program using PyCharm. I am using the (*) star operator in the following way in the parameters field of the run/debug configuration dialog box in PyCharm:
*.html
, but this doesn't work. I get the following error:
IOError: [Errno 2] No such file or directory: '*.html'
at the line where I open the file to read into my program. I think its reading the "*.html" literally as a file name. I'd appreciate your help in teaching me how to use the star operator in this case.
Addendum:
I'm pretty new to Python and Pycharm. I'm running my script using the following configuration options:
Now, I've tried different variations of parameters here, like '*.html', "*.html", and just *.html. I also tried glob.glob('*.html'), but the code takes it literally and thinks that the file name itself is "glob.glob('*.html')" and throws an error. I think this is more of a Pycharm thing than understanding bash or python. I guess what I want is to make Pycharm pass all the files of the directory through that parameters field in the picture. Is there some way for me to specify to Pycharm NOT to consider the string of parameters literally?
The way the files are being handled is by running a for loop through the sys.argv list and calling a function on each file. The function simply uses the open() method to read the contents of the file into a string so I can pull patterns out of the text. Hope that fleshes out the problem a bit better.
Filename expansion is a feature of bash. So if you call your python script from the linux command line, it will work, just like if you would have typed out all of the filenames as arguments to your script. Pycharm doesn't have this feature, so you will have to do that by yourself in your python script using a glob.
import glob
import sys
files = glob.glob(sys.argv[-1])
To keep compatibility between bash and pycharm, you can use something like this:
import glob
globs = ['*.html', '*.css', 'script.js']
files = []
for g in globs:
files.extend(glob.glob(g))
I have multiple arguments so this is what I did to allow for compatibility:
I have an argparse argument that returns an array of image file names. I check it as follows.
images = args["images"]
if len(images) == 1 and '*' in images[0]:
import glob
images = glob.glob(images[0])

Python3:Save File to Specified Location

I have a rather simple program that writes HTML code ready for use.
It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem.
Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)?
Extra cool-points if you know how to open a file browser window.
The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual.
import os
target_dir = r"C:\full\path\to\where\you\want\it"
fullname = os.path.join(target_dir,filename)
with open(fullname,"w") as f:
f.write("<html>....</html>")
import webbrowser
url = "file://"+fullname.replace("\\","/")
webbrowser.open(url,True,True)
BTW: the code is the same in python 2.6.
I'll admit I don't know Python 3, so I may be wrong, but in Python 2, you can just check the __file__ variable in your module to get the name of the file it was loaded from. Just create your file in that same directory (preferably using os.path.dirname and os.path.join to remain platform-independent).

Categories

Resources