Python os.isfile assert failing - python

So I'm having problems opening a file for reading, and so I decided to just try an os.isfile assert:
from Android_API_Parser import Android_API_Parser
import os.path
assert os.path.isfile("D:\Work\Python Workspace\Android_API_Parser\test.txt")
tester = Android_API_Parser()
tester.setFile("test.txt")
tester.parse()
It's failing the assert:
Traceback (most recent call last):
File "D:\Work\Python Workspace\Android_API_Parser\src\Android_API_Tester.py", line
9, in <module>
assert os.path.isfile("D:\Work\Python Workspace\Android_API_Parser\test.txt")
AssertionError
I have opened the path to the file I'm trying to open and pasted it below:
D:\Work\Python Workspace\Android_API_Parser\test.txt
Any ideas as to why it's even failing the assert? Unless I'm really tired, the file is clearly located there. I even tried both with "/" and "\", even with escape characters included.

In a string literal, you must escape backslashes with another backslash, use a raw string, or use forward slashes. Otherwise, "\t" becomes a string that just contains the tab character.
Try any of:
assert os.path.isfile("D:\\Work\\Python Workspace\\Android_API_Parser\\test.txt")
assert os.path.isfile(r"D:\Work\Python Workspace\Android_API_Parser\test.txt")
assert os.path.isfile("D:/Work/Python Workspace/Android_API_Parser/test.txt")
assert os.path.isfile(os.path.join("D:", "Work", "Python Workspace",
"Android_API_Parser", "test.txt"))
The file may also not be a regular file. Use os.path.exists to see if it exists.
You may also have insufficient privileges to see the file, or the file name you expect may be localized. To debug this, run:
path = ["Work", "Python Workspace", "Android_API_Parser", "test.txt"]
f = 'D:'
for p in path:
f = os.path.join(f, p)
print(f)
assert os.path.exists(f)
assert os.path.isfile(f)

Related

Problems with pickle python

I recently made a program using an external document with pickle. But when it tries to load the file with pickle, I got this error (the file is already existing but it also fails when the file in't existing):
python3.6 check-graph_amazon.py
a
b
g
URL to follow www.amazon.com
Product to follow Pool_table
h
i
[' www.amazon.com', ' Pool_table', []]
p
Traceback (most recent call last):
File "check-graph_amazon.py", line 17, in <module>
tab_simple = pickle.load(doc_simple)
io.UnsupportedOperation: read
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "check-graph_amazon.py", line 42, in <module>
pickle.dump(tab_simple, 'simple_data.dat')
TypeError: file must have a 'write' attribute
Here is the code :
import pickle5 as pickle
#import os
try:
print("a")
with open('simple_data.dat', 'rb') as doc_simple:
print("b")
tab_simple = pickle.load(doc_simple)
print("c")
print(tab_simple)
print("d")
URL = tab_simple[0]
produit_nom = tab_simple[1]
tous_jours = tab_simple[2]
print("f")
except :
print("g")
URL = str(input("URL to follow"))
produit_nom = str(input("Product to follow"))
with open('simple_data.dat', 'wb+') as doc_simple:
print("h")
#os.system('chmod +x simple_data.dat')
tab_simple = []
tab_simple.append(URL)
tab_simple.append(produit_nom)
tab_simple.append([])
print(tab_simple)
print("c'est le 2")
print("p")
pickle.dump(tab_simple, 'simple_data.dat')
print("q")
The prints are here to show which lines are executed. The os.system is here to allow writing on the file but the error is persisting.
I don't understand why it's said that the document doesn't have a write attribute because I opened it in writing mode. And I neither understand the first error where it can't load the file.
If it can help you the goal of this script is to initialise the program, with a try. It tries to open the document in reading mode in the try part and then set variables. If the document doesn't exist (because the program is lauched for the first time) it goes in the except part and create the document, before writing informations on it.
I hope you will have any clue, including changing the architecture of the code if you have a better way to make an initialisation for the 1st time the program is launched.
Thanks you in advance and sorry if the code isn't well formated, I'm a beginner with this website.
Quote from the docs for pickle.dump:
pickle.dumps(obj, protocol=None, *, fix_imports=True)
Write a pickled representation of obj to the open file object file. ...
...
The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.
So, you should pass to this function a file object, not a file name, like this:
with open("simple_data.dat", "wb"): as File:
pickle.dump(tab_simple, File)
Yeah, in your case the file has already been opened, so you should write to doc_simple.

'No such file or directory' ERROR information when using "PRINT"

When I 'print' some hex string, some interesting error information in python, I wonder why this error is caused.
Win10(I tried it on ubuntu, No ERROR),python 2.7
enc_hex = '''f982f01c'''
enc_ascii = enc_hex.decode('hex')
print(enc_ascii)
Traceback (most recent call last):
File ".\xxxx.py", line 7, in <module>
print(enc_ascii)
IOError: [Errno 2] No such file or directory
Well,in fact I want to know why "print" a special set of hex will cause file operation, other hex string will not error
Try using codecs.decode:
import codecs
enc_hex = '''f982f01c'''
enc_ascii = codecs.decode(enc_hex, 'hex')
print(enc_ascii)
Output:
b'\xf9\x82\xf0\x1c'
it seems like directory problems . in windows you have to use forward slash (/) while accessing the directory.similar was happened in my case then i use forward slash in windows then it works.

Compiled Extension File error Report in LiClipse Python

doc_holder_str = ''
sample_H_value = open("C:\testGupixwin\BX-N-H.HED", "r")
standard_conc_value = open("C:\testGupixwin\gupixwin_H_stdConc.txt", "r")
sample_H_value_str = sample_H_value.readline()
while sample_H_value_str is not '' :
stripper_sample_H = float(sample_H_value_str[5:].lstrip(' '))
I'm trying to write a piece of code (as shown above) which reads some values, do some calculations on it and returns the said values. I am using the LiClipse IDE, for python.
I have tested my code and it works, but when I tried to run it with real data, ( for which I created a new folder to put in all the files I will be working with) I received an OS error suggesting I inserted an invalid argument.
The error report says ;
Traceback (most recent call last):
File "C:\Python34\workspace\Gupixwin_Project.py", line 11, in <module>
sample_H_value = open("C:\testGupixwin\BX-N-H.HED", "r")
OSError: [Errno 22] Invalid argument: 'C:\testGupixwin\\BX-N-H.HED'
on clicking on the C:\testGupixwin\\BX-N-H.HED it bring up a message box suggesting, and I quote,
The definition was found at C:\testGupixwin\BX-N-H.HED, (which
cannot be opened because it is a compiled extension)
I must point out that I feel the error is that the system sees ...\\BX-N.... Instead of ..\BX-N... Which I expect.
Some one suggested I do this
[Open Window -> Preferences, goto PyDev -> Editor -> Code Style ->
File Types, look for "Valid source files (comma-separated)" and append
", log".]
I HAVE DONE THIS BUT I STILL GET THE OSERROR REPORT.
Thanks for any assistance
I think the problem is the escaping with \
alternate the string in: open("C:\testGupixwin\BX-N-H.HED", "r")
with:
open( r"C:\testGupixwin\BX-N-H.HED", "r" ) #rawstring
# or
open( "C:\\testGupixwin\\BX-N-H.HED", "r" ) #escaping the '\' with '\'
(also do this in the following line)

python sqlite3 connection path with spaces

I am trying to connect with a full path but I get this problem
>>> path = "/home/astro/Fun LAB/DBlist"
>>> db = sql.connect(path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: unable to open database file
>>>
i 've also tried this
>>> path = "/home/astro/Fun\ LAB/DBlist"
>>> db = sql.connect(path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: unable to open database file
>>>
I know it's because of the whitespace cause I've tried this and it works
>>> path = "/home/astro/DBlist"
>>> db = sql.connect(path)
>>>
so is there is an easy way to escape the whitespaces in the path or am I doing something wrong?
You might try the uri style approach - it worked for me in getting past connection issues due to spaces in file paths with sqlite3:
Escaping the spaces with %20
prefixing the path with file:///
Examples:
file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
file:///C:/Documents%20and%20Settings/fred/Desktop/
I would suggest naming files or folders without spaces. (I don't think it's possible either) Instead, use dash or underscores.
The next problem is to see where you're running your Python interpreter. If it's nested inside a directory and you're trying to create a path from the outside, then your link would raise an error.
>>> path = "/home/astro/Fun LAB/DBlist"
or
>>> path = "/home/astro/Fun\ LAB/DBlist"
or
>>> path = "/home/astro/DBlist"
wouldn't work if you run python inside these directories or from another.
To correct this, try:
>>> path = "../home/path/to/file"
Having spaces is indeed a problem.
I would suggest bring a symlink and work with that:
!ln -sf '$path_to_db_file' .
db = sql.connect('db_file')

Error while trying to use wmi objects (python)

I'm trying to write a script which detects whether the machine that the script is run on is a virtual machine or a physical machine and I don't understand the error and how to fix it.
import wmi
def sys_info():
objWMIService = wmi.GetObject("winmgmts:\root\cimv2")
colItems = objWMIService.ExecQuery("Select * from Win32_BaseBoard")
for objItem in colItems:
print "inside"
Manufacturer = objItem.Manufacturer
if Manufacturer == "Microsoft Corporation":
print "Virtual Machine"
else:
print "Not in one"
The error:
Traceback (most recent call last):
File "C:\Documents and Settings\xxx\Desktop\Python\Practice Code\System information\trial.py", line 16, in <module>
sys_info()
File "C:\Documents and Settings\xxx\Desktop\Python\Practice Code\System information\trial.py", line 5, in sys_info
objWMIService = wmi.GetObject("winmgmts:""\root\cimv2")
File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 72, in GetObject
return Moniker(Pathname, clsctx)
File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 87, in Moniker
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
com_error: (-2147217375, 'OLE error 0x80041021', None, None)
I'm hoping someone can help, I'm pretty new to python. Thanks.
Do things improve if you change:
objWMIService = wmi.GetObject("winmgmts:\root\cimv2")
to
objWMIService = wmi.GetObject(r"winmgmts:\root\cimv2")
The '\r' sequence in '\root' will be interpreted as a <CR> character in your code. You either have to doubleup the '\'s to escape them so they will be treated as backslashes, or precede the first double quote with 'r' (as I have done), to indicate to Python that this should be a "raw" string literal. Raw strings are no different from regular strings, but the raw string syntax tells the Python compiler to not interpret backslashes.

Categories

Resources