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 !
Related
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 currently have the following code which gets only the first column of each line of a file and puts it in a list:
GetTimes = [x.split(' ')[0] for x in open(logfile).readlines()]
The problem is, I now want to grab the first two columns of each line of a file. and below is the code I'm attempting to use:
GetTimes = [x.split(' ')[:2] for x in open(logfile).readlines()]
list(GetTimes)[0][0] + " " + list(GetTimes)[0][1]
Where I get stuck is I don't know how to incorporate the above line that begins with "list" with the original GetTimes line of code.
UPDATE:
there is a log file that has the date stamp below:
2018-06-27 08:53:45 affa fafa faf afafaf
2018-06-27 08:53:45 affa fafa faf afafaf
I was getting only the value in the first column, which is 2018-06-27. But, now, i want to get first and second column, and put them in a list.
below is my attempt:
def thetimes():
mylist = []
for ealltime in GetTimes:
combing = ealltime[0:20]
lineTstamps = list(combing[0] + " " + combing[1])
mylist.append(lineTstamps)
return mylist
print thetimes()
But when I run the above, i get this:
Traceback (most recent call last):
File "./scans.py", line 353, in <module>
print thetimes()
File "./scans.py", line 350, in livestatuslogTimes
lineTstamps = list(combing[0] + " " + combing[1])
IndexError: list index out of range
What am i doing wrong?
Your GetTimes = [x.split(' ')[:2] for x in open(logfile).readlines()] works just fine to get the first two columns(words). Since you used a list comprehension you've created a list of lists.
Your next line: list(GetTimes)[0][0] + " " + list(GetTimes)[0][1] is redundant as you don't need to convert GetTimes into a list when it is already a list and then you are adding column one of row one + column two of row one. This is already what is stored at GetTimes[0].
Based off of the variable name im assuming the log file begins with a date/time stamps and that's what you're trying to grab? Effectively you can now index GetTimes[0:len(GetTimes)] to get the Date/time combo of a row and then further index GetTimes[0:len(GetTimes)][0] or GetTimes[0:len(GetTimes)][1] to get the specific date or time.
If you provide a bit more context as to what you're trying to do next after GetTimes we can help you incorporate it! Let us know!
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 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.
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.