Pathlib and stem - Attributerror - python

as part of a code I have function as follow:
def match_output(orig_path: Path,lines: Iterable[str],stem: str, delim: str,delim_pred: Callable[[int], bool],) -> Iterable:
n = 0
path = orig_path.with_stem(f'{orig_path.stem}_{stem}')
with path.open('w') as f:
for line in lines:
n_delim = line.count(delim)
matched = delim_pred(n_delim)
if matched:
f.write(line)
n += int(matched)
yield
logger.info(f'Number of {stem} lines: {n}')
However, I am getting attribute error, couldn't solve it, would appreciate any suggestion?
Traceback (most recent call last):
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 95, in <module>
main()
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 88, in main
process(
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 82, in process
for n_lines, _ in enumerate(zip(*iters)):
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 27, in match_output
path = orig_path.with_stem(f'{orig_path.stem}_{stem}')
AttributeError: 'WindowsPath' object has no attribute 'with_stem'
I am very new to Pathlib and stem, someone smarter than me recommended that I look into it so apologize if the question sounds newbie

path.with_stem() was introduced in Python 3.9. In previous versions (that support path objects) you can do it manually:
path = orig_path.with_name(f'{orig_path.stem}_{stem}{orig_path.suffix}')

Related

Can't convert tuple to string what can I do?

I am trying to turn to out_chars from tuple to string. However, it seems quite troublesome since there is while loop and the state defined its to be tuple. What should I do
I try def convertString but not succesful
out_chars = []
string = ()
for i, char_token in enumerate(computer_response_generator):
out_chars.append(chars[char_token])
print(possibly_escaped_char(out_chars), end='', flush=True)
states = forward_text(net, sess, states, relevance, vocab, chars[char_token])
if i >= max_length:
break
states = forward_text(net, sess, states, relevance, vocab, sanitize_text(vocab, "\n> "))
states = convertTuple(states)
string = convertTuple(out_chars)
print(Text_to_sp(string, states))
Traceback (most recent call last):
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 358, in <module>
main()
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 44, in main
sample_main(args)
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 92, in sample_main
args.relevance, args.temperature, args.topn, convertTuple)
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 169, in chatbot
print(Text_to_sp(string, states))
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/Text_to_speech.py", line 28, in Text_to_sp
myobj.save("welcome.mp3")
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gtts/tts.py", line 249, in save
self.write_to_fp(f)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gtts/tts.py", line 182, in write_to_fp
text_parts = self._tokenize(self.text)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gtts/tts.py", line 144, in _tokenize
text = text.strip()
AttributeError: 'tuple' object has no attribute 'strip'
Process finished with exit code 1
what does your tuple contains?? does it contain complex objects or simple strings numbers etc???
your problem is hard to understand from what you have posted above. but if you want o convert tuple to string you can do like this
new_str = ''.join(yourtuple)
I'm not sure that understand your question right, but if you want to make a string from tuple, its really simple.
def convertTuple(tup):
str = ''.join(tup)
return str
tuple = ('g', 'e', 'e', 'k', 's')
str = convertTuple(tuple)
print(str)
If you cannot ensure all the elements of the tuple are strings, you have to cast them.
''.join([str(elem) for elem in myTuple])

AttributeError: 'str' object has no attribute '__name__' Returned

I am looking to simply import a list of information via a CSV and to convert that into a simple action, however I'm getting the following error message:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sst/cases.py", line 217, in run_test_script
exec(self.code, self.context)
File "./randd/exec_tests.py", line 39, in <module>
use_csv("randd/testcases/login.csv")
File "./randd/exec_tests.py", line 31, in use_csv
wait_for(action_input, locator_from_xpath(str(locator_input)))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sst/actions.py", line 146, in inner
return func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sst/actions.py", line 926, in wait_for
return _wait_for(condition, False, _TIMEOUT, _POLL, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sst/actions.py", line 885, in _wait_for
if config._current_test_assertion_count is not None and 'assert' in condition.__name__:
AttributeError: 'str' object has no attribute '__name__'
Below is the Python code being used:
# Import Libs
import logging
import csv
import sys
import testdata
from sst.actions import (run_test, go_to, click_element, assert_displayed, wait_for, write_textfield, sleep)
from sst.locators import (find_within, locator_from_css_selector, locator_from_xpath)
logger = logging.getLogger("CSVTests")
def use_csv(csv_file_path):
#file = open(sys.argv[1], 'rb')
file = open(csv_file_path, 'rb')
testcase = csv.reader(file)
next(testcase)
for row in testcase:
testcase_id = row[0]
action_input = row[1]
locator_input = row[2]
detail = row[3]
description = row[4]
logger.debug(str(testcase_id))
print(action_input)
print(locator_input)
# print(wait_for(action_input, locator_from_xpath(locator_input)))
wait_for(action_input, locator_from_xpath(str(locator_input)))
file.close()
# Goto Build
go_to(testdata.get_base_url())
# Run Tests
use_csv("randd/testcases/login.csv")
Please see below a snippet of the CSV:
TestCase ID,Action,Element / Locator,Option/Text/Result,Description
1,assert_displayed,"//body//div[#class='container-fluid']//div[contains(#class,'box')]",n/a,Checking that the login box is displayed.
2,assert_displayed,"//body//div[#class='container-fluid']//div[contains(#class,'box')]/div[#class='icon-holder']",n/a,Checking that the Frog icon is displayed.
The error occurs because in the sst library code there is an access to __name__:
condition.__name__
And condition should not be a string object, but the current value received is actually a string.
My guess is that in your code, in the line:
wait_for(action_input, locator_from_xpath(str(locator_input)))
You dont' have to wrap locator_input into a str(), so:
wait_for(action_input, locator_from_xpath(locator_input))
should work

reading last line of txt file in python and change it into variable to make calculation

td = 'date of transaction.txt'
tf = 'current balance.txt'
tr = 'transaction record.txt'
for line in open(tf):pass
for line2 in open(td):pass
for line3 in open(tr):pass
print line2,line,line3
"""
so call recall back last record
"""
rd=raw_input('\ndate of transaction: ')
print "Choose a type of transaction to proceed... \n\tA.Withdrawal \n\tB.Deposit \n\tC.Cancel & exit"
slc=raw_input('type of transaction: ')
i=1
while (i>0):
if slc=="A" or slc=="B" or slc=="C":
i=0
else:
i=i+1
slc=raw_input('invalid selection, please choose again...(A/B/C): ')
if slc=="A":
rr=input('\namount of transaction: ')
Line_len = 10 # or however long a line is, since in my example they all looked the same
SEEK_END = 2
file = open(tf, "r")
file.seek(-Line_len, SEEK_END)
a = int(str(file.read(Line_len)).split(" ")[0].strip())
rf=a-rr
f1=open(tf, 'a+')
f1.write('\n'+rf)
f1.close()
d1=open(td, 'a+')
d1.write('\n'+rd)
d1.close
r1=open(tr, 'a+')
r1.write('\n-'+rr)
r1.close
else:
print 'later'
above is my code, the function is to get data(last line) from txt file and read it, get new data and write it to the txt file again by creating new line.
my txt file(current balance.txt) should look like this:
2894.00
2694.00
but when i try to use the last line which is 2694.00 to do calculation(rf=a-rr), it failed returning this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
file.seek(-Line_len, SEEK_END)
IOError: [Errno 22] Invalid argument
else if i use this code:
for line in open(tf):
pass
a = line
rf=a-rr
it return this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
rf=a-rr
TypeError: unsupported operand type(s) for -: 'str' and 'int'
I seriously have no idea why...please help me...
To obtain last line of the file, you can simple do
with open('my_file.txt') as file:
last_line = file.readlines()[-1]
#last_line is a string value pointing to last line, to convert it into float, you can do
number = float(last_line.strip('\n').strip(' '))
The function input is giving you a string. Try doing:
rf=a-float(rr)

Python Multiprocessing IndexError

I am trying to parallel process some file by reading chunks and process each chunk by using multiprocessing libraries. Following is my code:
from multiprocessing import Pool
from itertools import islice
import traceback
#Produce key value pairs (Date, Market_Share*Market_Share)
def Map(L):
results = []
for w in L:
temp = w.split(',')
Date = temp[0]
Share = float(temp[1][:-1])
ShareSquare = str(Share*Share)
results.append((Date,ShareSquare))
return results
if __name__=='__main__':
pool = Pool(2)
f = open('C:/Users/Daniel/Desktop/Project/Optiver/atchm_9450.csv','r')
fw = open('C:/Users/Daniel/Desktop/Project/Optiver/marketshare.csv','w')
f.readline()
while True:
next_n_lines = list(islice(f,16))
if not next_n_lines:
break
else:
l = pool.map(Map,next_n_lines)
f.close()
fw.close()
However, it produces index out of range error:
Traceback (most recent call last):
File "trial.py", line 29, in <module>
l = pool.map(Map,next_n_lines)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 558, in get
raise self._value
IndexError: list index out of range
The list object I passed into the Map function is something like ['6/26/2014,68.90\n', '6/27/2014,68.84\n', '6/30/2014,68.80\n'....]
It works correctly when there is no parallelism involved (pool is not invoked).
What possibly causes this behavior?
At first glance, only those two lines can raise this exception:
Date = temp[0]
Share = float(temp[1][:-1])
Try to check that w have enough data.

IndexError: list index out of range?

I have a problem, I need the help of everyone.
I read rar file (100mb) and process text file (include in rarfile).
import glob
import os
import UnRAR2
from os import path, access, R_OK
os.chdir("E:\\sms")
for file in glob.glob("*.rar"):
# extract test.txt to memory
entries = UnRAR2.RarFile(file).read_files('*.txt')
test_content = entries[0][1]
#print test_content
for line in test_content.split("\n"):
A=line.split(' ')
print A[1]
Result:
19009057
7030
9119
9119
....
....
bla...bla...
......
9119
9119
9119
7050
9119
Traceback (most recent call last):
File "E:\LAPTRINH\Android\adt-bundle-windows\eclipse\plugins\org.python.pydev_2.7.1.2012100913\pysrc\pydevd.py", line 1397, in <module>
debugger.run(setup['file'], None, None)
File "E:\LAPTRINH\Android\adt-bundle-windows\eclipse\plugins\org.python.pydev_2.7.1.2012100913\pysrc\pydevd.py", line 1090, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "C:\Users\The\Documents\workspace\unrar\test_unrar.py", line 13, in <module>
print A[1]
IndexError: list index out of range
Please, help me!
Thank you!!!
One of your lines (probably your last) is not in the format you expect. Do this in your inner for loop:
A=line.split(' ')
if len(A) > 1:
print A[1]
A[1] would be suspect if the last line in your file was \n. You'd want to rethink the way you're pulling info back.
The error is telling you that the content of line split up, A, doesn't have a second item, which means that it doesn't have anything left to parse, and you're at the end of the file.

Categories

Resources