Python - comparing imported values - python-3.x

I would like to import the list from the file, read it line by line (already works). Each line containing a string representing a list.
I have to execute couple of tasks on it, however I got twisted and I dont know why below doesn't work. It gives me the following error :
ErrorCode:
Traceback (most recent call last):
File "main.py", line 8, in <module>
if len(n) != len(str(n + 1)):
TypeError: must be str, not int
f = open('listy.txt', 'r')
content = f.read().split('\n')
for n in content:
n.split(',')
## checking lengh
if len(n) != len(str(n + 1)):
print('Different lengh')
else:
print('All fine.')

Change
n.split(',')
if len(n) != len(str(n + 1)):
to:
n = n.split(',')
len(n[0]) != len(n[1]):
and don't forget to close your file with a f.close()
Better even, use with, example:
with open('listy.txt', 'r') as f:
content = f.read().split('\n')
you do not need a close() method when using with

Related

How to fix the code about appending a number in the line?

I create a new column (name:Account) in the csv, then try to make a sequence (c = float(a) + float(b)) and for each number in sequence append to the original line in the csv, which is the value of the new column. Here is my code:
# -*- coding: utf-8 -*-
import csv
with open('./tradedate/2007date.csv') as inf:
reader = csv.reader(inf)
all = []
row = next(reader)
row.append('Amount')
all.append(row)
a =50
for i, line in enumerate(inf):
if i != 0:
size = sum(1 for _ in inf) # count the line number
for b in range(1, size+1):
c = float(a) + float(b) # create the sequence: in 1st line add 1, 2nd line add 2, 3rd line add 3...etc
line.append(c) # this is the error message: AttributeError: 'str' object has no attribute 'append'
all.append(line)
with open('main_test.csv', 'w', newline = '') as new_csv:
csv_writer = csv.writer(new_csv)
csv_writer.writerows(all)
The csv is like this:
日期,成交股數,成交金額,成交筆數,發行量加權股價指數,漲跌點數,Account
96/01/02,"5,738,692,838","141,743,085,172","1,093,711","7,920.80",97.08,51
96/01/03,"5,974,259,385","160,945,755,016","1,160,347","7,917.30",-3.50,52
96/01/04,"5,747,756,529","158,857,947,106","1,131,747","7,934.51",17.21,53
96/01/05,"5,202,769,867","143,781,214,318","1,046,480","7,835.57",-98.94,54
96/01/08,"4,314,344,739","115,425,522,734","888,324","7,736.71",-98.86,55
96/01/09,"4,533,381,664","120,582,511,893","905,970","7,790.01",53.30,56
The Error message is:
Traceback (most recent call last):
File "main.py", line 21, in <module>
line.append(c)
AttributeError: 'str' object has no attribute 'append'
Very thanks for any help!!
I'm a little confused why you're structuring your code this way, but the simplest fix would be to change the append (since you can't append to a string) to += a string version of c, i.e.
line += str(c)
or
line += ',{}'.format(c)
(I'm not clear based on how you're written this if you need the comma or not)
The biggest problem is that you're not using your csv reader - below is a better implementation. With the csv reader it's cleaner to do the append that you want to do versus using the file object directly.
import csv
with open('./tradedate/2007date.csv') as old_csv:
with open('main_test.csv', 'w') as new_csv:
writer = csv.writer(new_csv, lineterminator='\n')
reader = csv.reader(old_csv)
all = []
row = next(reader)
row.append('Line Number')
all.append(row)
line_number = 51
for row in reader:
row.append(line_number)
all.append(row)
line_number += 1
writer.writerows(all)

I/O operation closed on file in python

I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error

"AssertionError: write() argument must be a bytes instance" when running WSGISOAPHandler

I have a SOAP server with pysimplesoap in Python 3.
Code
from wsgiref.simple_server import make_server
application = WSGISOAPHandler(dispatcher)
wsgid = make_server('', 8008, application)
wsgid.serve_forever()
I don't know why am I get the following error.
Error
Traceback (most recent call last):
File "/usr/lib/python3.4/wsgiref/handlers.py", line 138, in run
self.finish_response()
File "/usr/lib/python3.4/wsgiref/handlers.py", line 180, in finish_response
self.write(data)
File "/usr/lib/python3.4/wsgiref/handlers.py", line 266, in write
"write() argument must be a bytes instance"
AssertionError: write() argument must be a bytes instance
It's all because of WSGI is made for Python 2, so you can face some troubles using it in Python 3. If you dont want to change library's behavior like in first answer, workaround is to encode() all text data like:
def application(environ,start_response):
response_body = 'Hello World'
return [response_body.encode()]
Wsgi framework is built around Python 2. Therefore, if there is stuff in your program that does not include Python 3 dependencies, run the app with Python 2.
in "handlers.py" line 180
self.write(data.encode()) instead of self.write(data)
In my case the problem turned out to be that I was unintentionally outputting an object instead of a string. Fixed by encoding my result as a string via json.dumps(obj).
+++ pysimplesoap/server.py
e['name'] = k
if array:
e[:] = {'minOccurs': "0", 'maxOccurs': "unbounded"}
- if v in TYPE_MAP.keys():
- t = 'xsd:%s' % TYPE_MAP[v]
- elif v is None:
+
+ # check list and dict first to avoid
+ # TypeError: unhashable type: 'list' or
+ # TypeError: unhashable type: 'dict'
+ if v is None:
t = 'xsd:anyType'
elif isinstance(v, list):
n = "ArrayOf%s%s" % (name, k)
n = "%s%s" % (name, k)
parse_element(n, v.items(), complex=True)
t = "tns:%s" % n
+ elif v in TYPE_MAP.keys():
+ t = 'xsd:%s' % TYPE_MAP[v]
else:
raise TypeError("unknonw type v for marshalling" % str(v))
e.add_attribute('type', t)

Python web app getting valueerror 0 not in list

#app.route('/')
def index():
tpopDloads = popDloads
tpopShipped = popShipped
locPopDload = []
locPopShipped = []
popDinfo = []
popSinfo = []
popDloadsOrd = sorted(tpopDloads, reverse=True)
popShippedOrd = sorted(tpopShipped, reverse=True)
for i in range(3):
locPopDload.append(tpopDloads.index(popDloadsOrd[i]))
popDinfo.append(dProducts[locPopDload[i]])
tpopDloads[tpopDloads.index(popDloadsOrd[i])] = -1 #Problem line#
for i in range(3):
locPopShipped.append(tpopShipped.index(popShippedOrd[i]))
popSinfo.append(sProducts[locPopShipped[i]])
tpopShipped[tpopShipped.index(popDloadsOrd[i])] = -1
return render_template('index.html', popDinfo=popDinfo, popSinfo=popSinfo)
The error I'm getting is:
File "/var/lib/openshift/5697165a0c1e66eb870000fb/app-root/runtime /repo/flaskapp.py", line 47, in index
tpopShipped[tpopShipped.index(popDloadsOrd[i])] = -1
ValueError: 0 is not in list
This is using two variable that are popDloads and popShipped which are both lists that contain a set of integers. I don't see why it's not working as it is trying to find the actual index of a number after the list has been ordered. It also works when the numbers are all zero, it's only after I change the numbers in another piece of code that I run into problems.
The error is telling you why your code isn't working. 0 isn't in the list tpopShipped.
>>> [1,2,3].index(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 0 is not in list

ZipFile cracker works with a few combinations and crashes when many combinations are used

I've found many examples of zip crackers written in python, but unfortunatelly they were either written in python2 or have the functionality I do not need (i.e. use of dictionaries saved in files). For me was interesting to check how long and how much memory will it take to break, let's say, a password of 5-10 different symbols (a-z, a-zA-Z, a-zA-Z1-10 etc.). Afterwards I can try different libraries and techniques (threads etc.) to improve performance of the code and, hopefully, get better undestaning of python mechanics in the process.
Here is my program. It works well when the program tries 2-position passwords (a-zA-Z) and crashes with longer passwords.
import os
import shutil
import zipfile
from itertools import permutations, combinations_with_replacement
from string import ascii_letters
#passgen() yields passwords to be checked
def passgen(passminlength, passmaxlength,searchdict):
prevpwd = []
for n in range(passminlength,passmaxlength):
for p in combinations_with_replacement(searchdict,n):
for k in permutations(p,n):
pwd_tmp=''.join(k)
if prevpwd != pwd_tmp: #without this check passgen() yields
prevpwd = pwd_tmp #recurring password combinations
yield pwd_tmp #due to the logic behind permutations()
if __name__ == '__main__':
zFile = zipfile.ZipFile("secret.zip", 'r') #encrypted file to crack
pwd = None #password to find
output_directory = os.path.curdir+"/unzip_tmp" #output tmpfolder for extracted files
if not os.path.isdir(output_directory): #if it exists - delete, otherwise - create
os.makedirs('unzip_tmp')
else:
shutil.rmtree(output_directory)
os.makedirs('unzip_tmp')
searchdict = list(ascii_letters) #list with symbols for brute force: a-zA-Z
passminlength = 1
passmaxlength = 3 #code works with passmaxlength=2, doesn't - with passmaxlength=3
pwd_tmp = passgen(passminlength,passmaxlength,searchdict) #pwd_tmp is an iterator
while True:
try:
tmp = next(pwd_tmp)
except StopIteration: #iterator is empty-> quit while-loop
break
print("trying..:%s" % tmp)
zFile.setpassword(bytes(tmp,'ascii'))
try:
zFile.extractall(output_directory)
pwd = tmp
break #password is found->quit while-loop
except RuntimeError: #checked password is wrong ->go again though while loop
print("wrong password:%s" % tmp)
print("password is:%s" % pwd)
The program crashes with maxpasslength=3 on the row with "zFile.extractall(output_directory)".
Error is:
Traceback (most recent call last):
File "C:\Experiments\Eclipse\Workspace\messingaroundpython\zipcracker.py", lin
e 48, in <module>
zFile.extractall(output_directory)
File "C:\Python34\lib\zipfile.py", line 1240, in extractall
self.extract(zipinfo, path, pwd)
File "C:\Python34\lib\zipfile.py", line 1228, in extract
return self._extract_member(member, path, pwd)
File "C:\Python34\lib\zipfile.py", line 1292, in _extract_member
shutil.copyfileobj(source, target)
File "C:\Python34\lib\shutil.py", line 67, in copyfileobj
buf = fsrc.read(length)
File "C:\Python34\lib\zipfile.py", line 763, in read
data = self._read1(n)
File "C:\Python34\lib\zipfile.py", line 839, in _read1
data = self._decompressor.decompress(data, n)
zlib.error: Error -3 while decompressing data: invalid distance too far back
I am stuck. Any idea what I could be missing?
Update: It seems to be a bug from zlib. I added an exeption catcher to ignore bad combinations:
except RuntimeError: #checked password is wrong ->go again though while loop
print("wrong password:%s" % tmp)
except Exception as err:
print("zlib bug, wrong password?:%s" % tmp)
Now the program can process much longer passwords.

Resources