I hope someone can point out where I have gone wrong. I am looking to iterate through the 'mylist' list to grab the first entry and use that first entry as a search string, then perform a search and gather particular information once the string is found and post it to an Excel worksheet. Then I am hoping to iterate to the next 'mylist' entry and perform another search. The first iteration performs ok, but with the second iteration of the loop I get the following CMD window error...
2014 Apr 25 09:43:42.080 INFORMATION FOR A
14.01
Traceback (most recent call last):
File "C:\TEST.py", line 362, in <module>
duta()
File "C:\TEST.py", line 128, in duta
if split[10] == 'A':
IndexError: list index out of range
Exception RuntimeError: RuntimeError('sys.meta_path must be a list of
import hooks',) in <bound method Workbook.__del__ of
<xlsxwriter.workbook.Workbook object at 0x0238C310>> ignored
Here's my code...
for root, subFolders, files in chain.from_iterable(os.walk(path) for path in paths):
for filename in files:
if filename.endswith('.txt'):
with open(os.path.join(root, filename), 'r') as fBMA:
searchlinesBMA = fBMA.readlines()
fBMA.close()
row_numBMAA+=1
num = 1
b = 1
print len(mylist)
print (mylist[num])
while b<len(mylist):
for i, line in enumerate(searchlinesBMA):
for word in [mylist[num]]:
if word in line:
keylineBMA = searchlinesBMA[i-2]
Rline = searchlinesBMA[i+10]
Rline = re.sub('[()]', '', Rline)
valueR = Rline.split()
split = keylineBMA.split()
if split[6] == 'A':
print keylineBMA
print valueR[3]
worksheetFILTERA.write(row_numBMAA,3,valueR[3], decimal_format)
row_numBMAA+=1
break
num+=1
b=+1
Any ideas as to what I am doing wrong? Is my loop out of position, or am I not inputting the correct list pointer?
Thanks,
MikG
In my experience, this error is related to garbage collecting out of order. I saw it once when I was debugging code where someone was writing to files in a __del__ method. (Bad idea). I'm pretty sure you're getting the error because you're closing the file inside a with: block, which does the open and close for you.
On the second run, you got split = keylineBMA.split() with a result shorter than you expected. You try to access index 10 which is outside the list.
Related
I have been playing around with Python for over a year now and written several automation codes which I use on a daily basis. I have been writing this auto typer for Python, here is the code:
import pyautogui as pt
from time import sleep
empty_file = "C:\\Users\\Lucas\\Desktop\\PycharmProjects\\Automate\\main\\screenshots\\empty_file.png"
text_write = "C:\\Users\\Lucas\\Desktop\\PycharmProjects\\Automate\\main\\text_write.txt"
with open(text_write, 'r') as f:
text = f.read()
sentence = text.split("\n")
position0 = pt.locateOnScreen(empty_file, confidence=.8)
x = position0[0]
y = position0[1]
pt.moveTo(x, y, duration=.05)
pt.leftClick()
def post_text():
pt.moveTo(x-370, y+95, duration=.1)
for lines in range(len(text)):
pt.typewrite(str(sentence[lines],) + "\n", interval=.01)
with pt.hold('shift'):
pt.press('tab', presses=5)
sleep(2)
post_text()
The code completely works but at the end instead of the code breaking it gives me this error:
C:\Users\Lucas\PycharmProjects\wechat_bot\venv\Scripts\python.exe C:/Users/Lucas/Desktop/PycharmProjects/Automate/main/auto_typer.py
Traceback (most recent call last):
File "C:\Users\Lucas\Desktop\PycharmProjects\Automate\main\auto_typer.py", line 26, in <module>
post_text()
File "C:\Users\Lucas\Desktop\PycharmProjects\Automate\main\auto_typer.py", line 20, in post_text
pt.typewrite(str(sentence[lines],) + "\n", interval=.01)
IndexError: list index out of range
Process finished with exit code 1
I suspect the issue has to do specifically with the line:
str(sentence[lines],
I haven't found a solution yet. Am I supposed to be using len() or would and if else statement be better?
The problem is that you are doing
for lines in range(len(text)):
but then you later do
sentence[lines]
This will only work text is shorter than or the same length as sentence. But there is no such guarantee in your code.
Instead, you should do
for lines in range(len(sentence)):
Or better yet loop over the lines without indexes:
for line in sentence:
And then you can just do line instead of sentence[lines].
I am trying to execute a python script which is giving me an IndexError. I understood that the rsplit() method failed to split the string. I don't exactly know why it is showing index out of range. Could anyone tell me how to solve this problem ?
code
raw_directory = 'results/'
for name in glob.glob(raw_directory + '*.x*'):
try:
#with open(name) as g:
# pass
print(name)
reaction_mechanism = 'gri30.xml' #'mech.cti'
gas = ct.Solution(reaction_mechanism)
f = ct.CounterflowDiffusionFlame(gas, width=1.)
name_only = name.rsplit('\\',1)[1] #delete directory in filename
file_name = name_only
f.restore(filename=raw_directory + file_name, name='diff1D', loglevel=0)
Output
If I delete the file strain_loop_07.xml, I got the same error with another file.
results/strain_loop_07.xml
Traceback (most recent call last):
File "code.py", line 38, in <module>
name_only = name.rsplit('\\'1)[1] #delete directory in filename
IndexError: list index out of range
If rsplit failed to split the string, it returns an array with only one solution, so the [0] and not [1]
I understood in reply of this post that "name" variable is filled with text like "result/strain_loop_07.xml", so you want to rsplit that, with a line more like
name_only = name.rsplit('/', 1)[1]
So you'll get the "strain_loop_07.xml" element, which is what you probably wanted, because name.resplit('/', 1) return something like
['result', 'strain_loop_07.xml']
By the way, don't hesitate to print your variable midway for debuging, that is often the thing to do, to understand the state of your variable at a specific timing. Here right before your split !
I'm working on a game in Python and at the end, scores are written to a file and then the top 5 scores are extracted from the file. This usually works perfectly fine but once I reset the high scores I get an Index error saying "the list index is out of range"
Traceback (most recent call last):
File "/home/leo/Documents/Python/infinitest/infinitest.py", line 172, in <module>
scoreboard()
File "/home/leo/Documents/Python/infinitest/infinitest.py", line 147, in scoreboard
print("{0[0]} : {1[0]}\n{0[1]} : {1[1]}\n{0[2]} : {1[2]}\n{0[3]} : {1[3]}\n{0[4]} : {1[4]}".format(scores,names))
IndexError: list index out of range
How would I fix this
def scoreboard():
c = add_up1(False)
d = add_up2(False)
with open("/home/leo/Documents/Python/infinitest/hi2.txt", "a+") as leaders:
leaders.write('{},{}\n'.format(c,name1))
leaders.write('{},{}\n'.format(d,name2))
line=leaders.readline()
dic={}
for line in leaders:
data = line.split(",")
dic[int(data[0])] = data[1]
dic1={}
for key in sorted(dic.keys()):
dic1[key]=dic[key]
scores=list(dic1.keys())
names=list(dic1.values())
names =names[::-1]
scores= scores[::-1]
print("{0[0]} : {1[0]}\n{0[1]} : {1[1]}\n{0[2]} :{1[2]}\n{0[3]} : {1[3]}\n{0[4]} : {1[4]}".format(scores,names))
In the external file, it is formatted so there is the score, followed by a comma, followed by a
username. For example:
100,exampleuser
The add_up functions are fine and just return the total score.
I've tried to add placeholder scores to fix the problem, like
1,Placeholder1
2,Placeholder2
3,Placeholder3
4,Placeholder4
5,Placeholder5
and this sometimes work but now is not working again.
After writing to the file its position is at the end - you can see that with leaders.tell(). When you start reading, the for loop exits immediately because there are no more lines and dic remains empty. Later, scores and names are empty so you get an IndexError when you try to access items.
Before starting to read the file set it's position back to the beginning - if there is a header that you don't want skip the first line:
...
leaders.seek(0)
#_ = next(leaders) # skip header
for line in leaders:
data = line.split(",")
dic[int(data[0])] = data[1]
I found this code on the internet, meant to search through text files in a zipped folder to find matches. I ran it in IDLE to see how it worked.. but I have a problem, and it seems to be this line:
fname = seed + ".txt"
The error message returns this:
Traceback (most recent call last):
File "C:/Users/[name]/AppData/Local/Programs/Python/Python36-32/zip2.py", line 10, in <module>
fname = seed + ".txt"
TypeError: can only concatenate tuple (not "str") to tuple
Here is the code:
import re
from zipfile import *
findnothing = re.compile(r"Next nothing is (\d+)").match
comments = []
z = ZipFile("channel.zip", "r")
seed = "90052"
while True:
fname = seed + ".txt"
comments.append(z.getinfo(fname).comment)
guts = z.read(fname)
m = findnothing(guts.decode('utf-8'))
if m:
seed = m.groups(1)
else:
break
print("".join(comments))
I've searched stackoverflow, and have found nothing similar to my issue. Most of them state that a comma in a variable usually causes the compiler to treat it as a tuple. I don't understand why it is saying seed is a tuple. There is no comma, no parenthesis, or anything else that would define it as a tuple to the Python compiler. How can I fix this?
Thanks in advance
Change m.groups(1) to m.group(1) (singular, not plural). Per the docs at https://docs.python.org/3.6/library/re.html#re.match.groups , group returns a single match but groups returns a tuple of all matches. You are getting the error the second time through the loop, when seed has been replaced by the output of groups, which is a tuple.
First, re.match only matches at the start of the string. Make sure you didn't mean to use re.search instead!
Second, m.groups(1) returns a tuple like ('12345',). Try seed = m.groups(1)[0] instead.
I'm trying to write some code that searches through a directory and pulls out all the items that start with a certain numbers (defined by a list) and that end with '.labels.txt'. This is what I have so far.
lbldir = '/musc.repo/Data/shared/my_labeled_images/labeled_image_maps/'
picnum = []
for ii in os.listdir(picdir):
num = ii.rstrip('.png')
picnum.append(num)
lblpath = []
for file in os.listdir(lbldir):
if fnmatch.fnmatch(file, '*.labels.txt') and fnmatch.fnmatch(file, ii in picnum + '.*'):
lblpath.append(os.path.abspath(file))
Here is the error I get
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-a03c65e65a71> in <module>()
3 lblpath = []
4 for file in os.listdir(lbldir):
----> 5 if fnmatch.fnmatch(file, '*.labels.txt') and fnmatch.fnmatch(file, ii in picnum + '.*'):
6 lblpath.append(os.path.abspath(file))
TypeError: can only concatenate list (not "str") to list
I realize the ii in picnum part won't work but I don't know how to get around it. Can this be accomplished with the fnmatch module or do I need regular expressions?
The error comes because you are trying to add ".*" (a string) to the end of picnum, which is a list, and not a string.
Also, ii in picnum isn't giving you back each item of picnum, because you are not iterating over ii. It just has the last value that it was assigned in your first loop.
Instead of testing both at once with the and, you might have a nested test that operates when you find a file matching .labels.txt, as below. This uses re instead of fnmatch to extract the digits from the beginning of the file name, instead of trying to match each picnum. This replaces your second loop:
import re
for file in os.listdir(lbldir):
if file.endswith('.labels.txt')
startnum=re.match("\d+",file)
if startnum and startnum.group(0) in picnum:
lblpath.append(os.path.abspath(file))
I think that should work, but it is obviously untested without your actual file names.