I trying to do the simple script and its throwing the below error at for loop,
WASX7017E: Exception received while running file "/abc/websphere/wasad/createusers.py";
exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
File "<string>", line 22, in ?
AttributeError: __getitem__
filename=sys.argv[0]
file_read= open( filename) ---- this is line 22
for row in file_read:
Please let me know the reason for this.
Here you can find my code,
import sys
filename="/usr/websphere/onefolder/Userlist.txt"
fileread = open(filename, 'r')
for row in fileread:
column=row.strip().split(';')
user_name=column[0]
pass_word=column[1]
AdminTask.createUser(['-uid',user_name, '-password', pass_word, '-confirmPassword', pass_word])
AdminTask.mapUsersToAdminRole(['-roleName','Administrator','-userids',user_name])
AdminTask.addMemberToGroup('[-memberUniqueName user_name,o=defaultWIMFileBasedRealm -groupUniqueName cn=webarch,o=defaultWIMFileBasedRealm]')
fileread.close()
AdminConfig.save()
print 'Saving Configuration is completed'
It looks like you want to iterate over each line in the file. The open method in Python returns a file object. If you want to iterate over each line in the file, you'll need to call readlines to retrieve the contents of the file, and then loop over that.
This should work:
import sys
filename="/usr/websphere/onefolder/Userlist.txt"
fileread = open(filename, 'r')
filelines = fileread.readlines()
for row in filelines:
column=row.strip().split(';')
user_name=column[0]
pass_word=column[1]
AdminTask.createUser(['-uid',user_name, '-password', pass_word, '-confirmPassword', pass_word])
AdminTask.mapUsersToAdminRole(['-roleName','Administrator','-userids',user_name])
AdminTask.addMemberToGroup('[-memberUniqueName user_name,o=defaultWIMFileBasedRealm -groupUniqueName cn=webarch,o=defaultWIMFileBasedRealm]')
fileread.close()
AdminConfig.save()
print 'Saving Configuration is completed'
Related
I am trying to get the code below to read the file raw.txt, split it by lines and save every individual line as a .txt file. I then want to append every text file to splits.zip, and delete them after appending so that the only thing remaining when the process is done is the splits.zip, which can then be moved elsewhere to be unzipped. With the current code, I get the following error:
Traceback (most recent call last): File "/Users/Simon/PycharmProjects/text-tools/file-splitter-txt.py",
line 13, in <module> at stonehenge summoning the all father. z.write(new_file)
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 1123, in write st = os.stat(filename) TypeError: coercing to Unicode: need string or buffer,
file found
My code:
import zipfile
import os
z = zipfile.ZipFile("splits.zip", "w")
count = 0
with open('raw.txt','r') as infile:
for line in infile:
print line
count +=1
with open(str(count) + '.txt','w') as new_file:
new_file.write(str(line))
z.write(new_file)
os.remove(new_file)
You could simply use writestr to write a string directly into the zipFile. For example:
zf.writestr(str(count) + '.txt', str(line), compress_type=...)
Use the file name like below. write method expects the filename and remove expects path. But you have given the file (file_name)
z.write(str(count) + '.txt')
os.remove(str(count) + '.txt')
So, i've been writing this program that takes a HTMl file, replaces some text and puts the return back into a different file in a different directory.
This error happened.
Traceback (most recent call last):
File "/Users/Glenn/jack/HTML_Task/src/HTML Rewriter.py", line 19, in <module>
with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/posixpath.py", line 89, in join
genericpath._check_arg_types('join', a, *p)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/genericpath.py", line 143, in _check_arg_types
(funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'TextIOWrapper'
Below is my code. Has anyone got any solutions I could implement, or should I kill it with fire.
import re
import os
os.mkdir ("dest")
file = open("2016-06-06_UK_BackToSchool.html").read()
text_filtered = re.sub(r'http://', '/', file)
print (text_filtered)
with open ("2016-06-06_UK_BackToSchool.html", "wt") as out_file:
print ("testtesttest")
with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)):
out_file.write(text_filtered)
os.rename("/Users/Glenn/jack/HTML_Task/src/2016-06-06_UK_BackToSchool.html", "/Users/Glenn/jack/HTML_Task/src/dest/2016-06-06_UK_BackToSchool.html")
with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)):
Here out_file if TextIOWrapper, not string.
os.path.join takes string as arguments.
Do not use keywords name as variable. file is keyword.
Do not use space in between function call os.mkdir ("dest")
try to change this:
with open ("2016-06-06_UK_BackToSchool.html", "wt") as out_file
on this:
with open ("2016-06-06_UK_BackToSchool.html", "w") as out_file:
or this:
with open ("2016-06-06_UK_BackToSchool.html", "wb") as out_file:
Im trying to read a dataset and collect meta features from it.
I get the following error after executing the python file.
Traceback (most recent call last):
File "runmeta.py", line 79, in <module>
np.savetxt('datasets/'+str(i)+'/metafeatures',meta[i],delimiter=',')
File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 940, in savetxt
fh = open(fname, 'w')
IOError: [Errno 2] No such file or directory: 'datasets/2/metafeatures'
the error you're getting is simply telling you it didn't find the file. i would suggest looking into absolute and relative file paths.
advice in error handling:
the error is triggered on this line
fh = open(fname, 'w')
so as you debug your program, look at the line python shows you. maybe change the variable fname. that is where i would start.
currently
fname = 'datasets/2/metafeatures'
So, I'm trying to unzip a .jar file using this code:
It won't unzip, only 20 / 500 files, and no folders/pictures
The same thing happens when I enter a .zip file in filename.
Any one any suggestions?
import zipfile
zfilename = "PhotoVieuwer.jar"
if zipfile.is_zipfile(zfilename):
print "%s is a valid zip file" % zfilename
else:
print "%s is not a valid zip file" % zfilename
print '-'*40
zfile = zipfile.ZipFile( zfilename, "r" )
zfile.printdir()
print '-'*40
for info in zfile.infolist():
fname = info.filename
data = zfile.read(fname)
if fname.endswith(".txt"):
print "These are the contents of %s:" % fname
print data
filename = fname
fout = open(filename, "w")
fout.write(data)
fout.close()
print "New file created --> %s" % filename
print '-'*40
But, it doesn't work, it unzips maybe 10 out of 500 files
Can anyone help me on fixing this?
Already Thanks!
I tried adding, what Python told me, I got this:
Oops! Your edit couldn't be submitted because:
body is limited to 30000 characters; you entered 153562
and only the error is :
Traceback (most recent call last):
File "C:\Python27\uc\TeStINGGFDSqAEZ.py", line 26, in <module>
fout = open(filename, "w")
IOError: [Errno 2] No such file or directory: 'net/minecraft/client/ClientBrandRetriever.class'
The files that get unzipped:
amw.Class
amx.Class
amz.Class
ana.Class
ane.Class
anf.Class
ang.Class
ank.Class
anm.Class
ann.Class
ano.Class
anq.Class
anr.Class
anx.Class
any.Class
anz.Class
aob.Class
aoc.Class
aod.Class
aoe.Class
This traceback tells you what you need to know:
Traceback (most recent call last):
File "C:\Python27\uc\TeStINGGFDSqAEZ.py", line 26, in <module>
fout = open(filename, "w")
IOError: [Errno 2] No such file or directory: 'net/minecraft/client/ClientBrandRetriever.class'
The error message says that either the file ClientBrandRetriever.class doesn't exist or the directory net/minecraft/client does not exist. When a file is opened for writing Python creates it, so it can't be a problem that the file does not exist. It must be the case that the directory does not exist.
Consider that this works
>>> open('temp.txt', 'w')
<open file 'temp.txt', mode 'w' at 0x015FF0D0>
but this doesn't, giving nearly identical traceback to the one you are getting:
>>> open('bogus/temp.txt', 'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'bogus/temp.txt'
Creating the directory fixes it:
>>> os.makedirs('bogus')
>>> open('bogus/temp.txt', 'w')
<open file 'bogus/temp.txt', mode 'w' at 0x01625D30>
Just prior to opening the file you should check if the directory exists and create it if necessary.
So to solve your problem, replace this
fout = open(filename, 'w')
with this
head, tail = os.path.split(filename) # isolate directory name
if not os.path.exists(head): # see if it exists
os.makedirs(head) # if not, create it
fout = open(filename, 'w')
If python -mzipfile -e PhotoVieuwer.jar dest works then you could:
import zipfile
with zipfile.ZipFile("PhotoVieuwer.jar") as z:
z.extractall()
I am reposting after changing a few things with my earlier post. thanks to all who gave suggestions earlier. I still have problems with it.
I have a data file (un-structed messy file) from which I have to scrub specific list of strings (delete strings).
Here is what I am doing but with no result:
infile = r"messy_data_file.txt"
outfile = r"cleaned_file.txt"
delete_list = ["firstname1 lastname1","firstname2 lastname2"....,"firstnamen lastnamen"]
fin = open(infile,"")
fout = open(outfile,"w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
When I execute the file, I get the following error:
NameError: name 'word' is not defined
I'm unable to replicate your error; the error I get with your code is the empty mode string - either put "r" or delete it, read is the default.
Traceback (most recent call last):
File "test.py", line 6, in <module>
fin = open(infile, "")
ValueError: empty mode string
Otherwise, seems fine!