My python script reads JSON information from a website, stores it in a file for processing, and should clean it in the end.
This was working without issues in other scripts, but for some reason, os.remove fails to delete the file in the end:
import urllib2, json
import os, sys, argparse
ref_list_tmpfile = '/tmp/reference.%s.txt' % os.getpid()
ref_list_response=urllib2.urlopen('http://localhost:11111/api/reference').read()
with open(ref_list_tmpfile,'w') as outfile:
outfile.write(ref_list_response)
ref_list_data=open(ref_list_tmpfile)
reference_list = json.load(ref_list_data)
ref_list_data.close()
.
.
.
.
os.remove(ref_list_tmpfile)
The main logic works well, but the error i'm getting refers to the last command (os.remove) and the file is not deleted:
Traceback (most recent call last):
File "./vm_creator.py", line 58, in <module>
os.remove(ref_list_tmpfile)
AttributeError: 'unicode' object has no attribute 'remove'
Any ideas?
You've redefined os to be a string, somewhere in the code you've snipped.
Related
is there a way to import multiple python files into a main python file?
I have a bunch of py files and each one has to run in the main python file and the data are saved into a json file.
This is what I tried and it gave me an error.
import light.py as light
Error:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/Desktop/majorproject/pillar1.py", line 8, in <module>
import sensorkey.py as sensorkey
ImportError: No module named 'sensorkey.py'; 'sensorkey' is not a package
I have also tried specifying the path to the py file and it didn't work either and keeps giving an invalid syntax error.
import /home/pi/Desktop/json/light.py as light
Update:
I managed to fix the import error but i now, after importing this light.py file, i have to print out certain keys from a dictionary (key) into this new file then export it to a json file. I'm currently using TinyDB to do so. Here are my codes:
from tinydb import TinyDB, Query
import json
from light import key
with open("/home/pi/Desktop/json/sensortestest.json", 'w+'):
db = TinyDB('/home/pi/Desktop/json/sensortestest.json')
table = db.table('Light')
db.insert_multiple([{'Key 1' :key[lightkey]}, {'Key 2' : key[lightkeyID]}])
Error:
Traceback (most recent call last):
File "/home/pi/Desktop/majorproject/testertestest.py", line 12, in <module>
db.insert_multiple([{'Key 1' :key[lightkey]}, {'Key 2' : key[lightkeyID]}])
NameError: name 'lightkey' is not defined
The problem is I had already defined 'lightkey' in its own file already.
To include the dictionary, you could do this if your file location is in different directory (with caution of path.append as #Coldspeed mentioned):
import sys
sys.path.append("path/foo/bar/")
from light import *
If it is in same directory as current directory, you could just do:
from light import *
The syntax for importing your_filename.py, assuming it is in the same directory, is
import your_filename
In your case, it would be
import light
Note the absence of .py.
If your file is in a different directory, you'll need to do:
import sys
sys.path.append('path/to/dir/containing/your_filename.py')
import your_filename
Note that appending to sys.path is dangerous, and should not be done unless you know what you're doing.
Read more at the official docs for import.
This question already has answers here:
Importing installed package from script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError
(2 answers)
Closed 7 months ago.
I am trying to parse JSON from Python. I recently started working with Python so I followed some stackoverflow tutorial how to parse JSON using Python and I came up with below code -
#!/usr/bin/python
import json
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
print j['script']
But whenever I run the above code, I always get this error -
Traceback (most recent call last):
File "json.py", line 2, in <module>
import json
File "/cygdrive/c/ZookPython/json.py", line 4, in <module>
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
AttributeError: 'module' object has no attribute 'loads'
Any thoughts what wrong I am doing here? I am running cygwin in windows and from there only I am running my python program. I am using Python 2.7.3
And is there any better and efficient way of parsing the JSON as well?
Update:-
Below code doesn't work if I remove the single quote since I am getting JSON string from some other method -
#!/usr/bin/python
import json
jsonStr = {"script":"#!/bin/bash echo Hello World"}
j = json.loads(jsonStr)
shell_script = j['script']
print shell_script
So before deserializing how to make sure, it has single quote as well?
This is the error I get -
Traceback (most recent call last):
File "jsontest.py", line 7, in <module>
j = json.loads(jsonStr)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
File "json.py", line 2, in <module>
import json
This line is a giveaway: you have named your script "json", but you are trying to import the builtin module called "json", since your script is in the current directory, it comes first in sys.path, and so that's the module that gets imported.
You need to rename your script to something else, preferrably not a standard python module.
It looks like you have a json.py module which is not part of the Standard Library. Not sure what ZookPython is. Try renaming ZookPython directory (or just json.py) and re-run.
I am trying to modify my file after fetching it from HDFS using pyspark and then i want to save it in HDFS for that i have written below code.
Code:
import subprocess
from subprocess import Popen, PIPE
from pyspark import SparkContext
cat = sc.textFile("/user/root/parsed.txt")
hrk = "#"
for line in cat.collect():
if (code == "ID"):
line =line.strip() + "|"+hrk
line.saveAsTextFile("/user/root/testsprk")
print(line)
But when i run the code i am getting below error.
Error:
Traceback (most recent call last):
File "<stdin>", line 30, in <module>
AttributeError: 'unicode' object has no attribute 'saveAsTextFile'
I know there is some issue with my line variable but i am not able to fix it.
It because you are collecting all data, it means that collection is not RDD, but normal list and line is just one string.
You shouldn't collect all data on driver. Instead, use RDD.map and then RDD.saveAsTextFile
def add_hrk_on_id(line):
if (code == "ID"):
return line.strip() + "|"+hrk
else
return line
cat.map(add_hrk_on_id).saveAsTextFile(path)
Trying to setup client Python script in my Windows system and finally i got stuck up with the below error, Tried in the Google and myself of about 4 hrs. But not able find out the solution. Since i am very new to the Python, I could not able to find out the solution.
Please have a look at below code and its error, So you may have solution for me,
Error:
C:\Python26>python C:\xampp\htdocs\cequel-dev\mbtools\main_inject.py
Traceback (most recent call last):
File "C:\xampp\htdocs\cequel-dev\mbtools\main_inject.py", line 12, in <module>
import injectdir
File "C:\xampp\htdocs\cequel-dev\mbtools\injectdir\__init__.py", line 10, in <module>
import action
File "C:\xampp\htdocs\cequel-dev\mbtools\injectdir\action\__init__.py", line 1, in <module>
from command import list
File "C:\xampp\htdocs\cequel-dev\mbtools\injectdir\action\command.py", line 28, in <module>
action_list[action.name]=action
AttributeError: 'module' object has no attribute 'name'
Code: (Line no: 19 to 28)
try:
action_list={}
for file in filenames:
if file.endswith('.py') and file != '__init__.py' and file != 'command.py':
#Import the file as a module action_imp
exec "import {0} as action_imp".format(file[0:-3])
#Get the action object from action_imp. Name is a required method for all actions
action=action_imp
#Put the file name in file_name
action.file_name=file[0:-3]
action_list[action.name]=action
except:
This seems like a array attribute error. So i have tried with if condition, But no luck so far.
So i have stuck with the last line ( "action_list[action.name]=action" ). Please let me know if you have any suggestions or any quick solution to suppress the error in the for loop.
Thanks.
As the comment after the exec statement says, every action has to have a name.
Ensure that every file listed in filenames (except __init__.py and command.py) contains a variable name.
Alternatively, you can suppress the error by replacing line 28 with:
try:
action_list[action.name]=action
except AttributeError:
print "Could not register action", action.file_name
Hi I am trying to rum a C *.o using python 2.6.5 as follows
import os
import sys
file_type = os.command('./file_type.o %s.txt 2>&1' % file_name)
And, it gives the error message :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'command'
Being a beginner this might be a very trivial question, I request for the direction / help.
There is no function named command in the os module, hence the error. You probably meant to call os.system() instead.
os.command() doesn't exist. It looks like you are looking for os.system()
os.command doesn't exist, using os.system instead.