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!
Related
I am attempting to create a loop that creates a file named "/tmp/newfile.txt" and creates 29 lines of text. Line 1 should read: "I see 0 sheep". For each line, 1 sheep should be added and a new line created to reflect that until 29 sheep (and lines) are reached.
x = 0
myDoc = myDoc.readfiles("/tmp/newfile.txt", "r+")
myDoc.write("I see" + str(x) + "sheep")
for line in myDoc.readfiles():
x = x + 1
myDoc.append(x)
print(myDoc)
if x == 30
break;
First, what I tried to do is create a new file and put it into a variable (myDoc) that would open it. I specified w+ so that I would have the ability to read the file and write on it. I gave the changing number a variable 'x'.
The function I intended to, for each line in the file, write "I see x sheep". Afterward, add 1 to the current value of x and append it so it's added to the file. After this, print it so I can see the line(s). Once that value reached 30, cease the loop because 29 is the number of lines I need.
My errors have to do with indentation and nothing being printed at all. I am extremely new to this.
Welcome to StackOverflow!
There seem to be a couple of issues in the code:
Indentation / Syntax Errors - It seems that you are using Python, which follows strict indentation and whitespace rules. An indent is inserted when you enter a new local scope / new control flow / enter an if/elif/else statement or a while or for loop, to separate it from the current scope.
You'd need to remove the space on the left side on line 3 and line 6.
Also, on line 8 there should be a colon(:) after the if x==30.
The mode used (w+) isn't going to work as expected.
This mode overwrites a file if it already exists and allows you to read and write to that file. Instead, you would need the r+ mode.
There's a great explanation & flowchart in this answer explaining the various file modes - https://stackoverflow.com/a/30566011/13307211
The for loop can't iterate over myDoc.
The open function gives a file object (TextIOWrapper), which can't be iterated over. You could use the myDoc.readfiles() method, which returns a list of lines present in the file and loop over that - for line in myDoc.readfiles().
printing myDoc and using .append() with myDoc wouldn't work as expected. It's representing a file object, which doesn't have an append method. Also, I feel like there might have been some mixed logic here - were you trying to iterate over myDoc like an array and hence pushing value to it?
I'd suggest removing the append part as the past value of x isn't going to be needed for what you want to do.
After applying the above, you should end up with code that looks like this -
x = 0
myDoc = open("./newfile.txt", "r+")
for line in myDoc.readlines():
myDoc.write("I see" + str(x) + "sheep\n")
x = x + 1
if x == 30:
break
Now, this doesn't exactly do what you want it to do...
The first thing we should do is update the for loop - a for loop should be structured in a way where it has a start, an end, and an increment, or it should iterate over a range of values. Python has a neat range function that allows you to iterate between values.
for x in range(1, 10):
print(x)
the above would print values from 1 to 10, excluding 10.
updating our for loop, we can change the code to -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep")
we could also use a while loop here -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep")
this makes the file but without the lines and without the right formatting. "I see " + str(x) + " sheep" should fix the sentence, but to print the string on multiple lines instead of the same line, you would need to use the newline character(\n) and add it at the end of the string -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep\n")
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 have the following problem:
I open a file and read it line by line searching for a specific pattern. When I found it, I would like to write the entire line AND THE NEXT TWO LINES into a new file. The problem is that I don't know how to get from the line that I've found to the next 2.
AAA
XXX
XXX
BBB
XXX
XXX
CCC
XXX
XXX
In this example it would be that I find "BBB" and I want to get the next two lines.
What could I do? Thank you very much for your kind help!
Edit: I realized that I have to ask more precisely.
This is the code from my colleague
for k in range(0,len(watcrd)):
if cvt[k]>cvmin:
intwat+=1
sumcv+=cvt[k]
sumtrj+=trj[k]/((i+1)*sep/100)
endline='%5.2f %5.2f' % (cvt[k],trj[k]/((i+1)*sep/100)) # ivan
ftrj.write(watline[k][:55]+endline+'\n')
fall.write(watline[k][:55]+endline+'\n')
For every k in range I would like to write k, k+1, k+2 to the file ftrj.
Which is the best way to do this?
Edit 2: I am sorry, but I realized that I've made a mistake. What you suggested worked, but I realized that I have to include it in a different part of the code.
for line in lines[model[i]:model[i+1]]:
if line.startswith('ATOM'):
resi=line[22:26]
resn=line[17:20]
atn=line[12:16]
crd=[float(line[31:38]),float(line[38:46]),float(line[46:54])]
if (resn in noprot)==False and atn.strip().startswith('CA')==True:
protcrd.append(crd)
if (resn in reswat)==True and (atn.strip() in atwat)==True:
watcrd.append(crd)
watline.append(line)
I would think of something like this:
(...)
if (resn in reswat)==True and (atn.strip() in atwat)==True:
watcrd.append(crd)
watline.append(line)
for i in range(1, 3):
try:
watcrd.append(crd[line + i])
watline.append(line[line + i])
except IndexError:
break
But it doesn't work. How can I indicate the part and the line that I want to append to this list?
Python file objects are iterators, you can always ask for the next lines:
with open(inputfilename) as infh:
for line in infh:
if line.strip() == 'BBB':
# Get next to lines:
print next(infh)
print next(infh)
Here next() function advances the infh iterator to the next line, returning that line.
However, you are not processing a file; you are processing a list instead; you can always access later indices in the list:
ftrj.write(watline[k][:55]+endline+'\n')
fall.write(watline[k][:55]+endline+'\n')
for i in range(1, 3):
try:
ftrj.write(watline[k + i][:55]+endline+'\n')
fall.write(watline[k + i][:55]+endline+'\n')
except IndexError:
# we ran out of lines in watline
break
I've recently gotten back into programming and decided as a project to get me going and motivated I was going to write a character editor for fallout 2. The issue I'm having is after the first few strings I can't seem to pull the data I need using the file offsets or structs.
This is what I am doing.
The file I Am working with is www.retro-gaming-world.com/SAVE.DAT
import struct
savefile = open('SAVE.DAT', 'rb')
try:
test = savefile.read()
finally:
savefile.close()
print 'Header: ' + test[0x00:0x18] # returns the save files header description "'FALLOUT SAVE FILE '"
print "Character Name: " + test[0x1D:0x20+4] Returns the characters name "f1nk"
print "Save game name: " + test[0x3D:0x1E+4] # isn't returning the save name "church" like expected
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0]) # is expected to return the current experience but gives the follosing error
output :
Header: FALLOUT SAVE FILE
Character Name: f1nk
Save game name:
Traceback (most recent call last):
File "test", line 11, in <module>
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0])
struct.error: unpack requires a string argument of length 2
I've confirmed the offsets but it just isn't returning anything as it is expected.
test[0x08:0x04] is an empty string because the end index is smaller than the starting index.
For example, test[0x08:0x0A] would give you two bytes as required by the h code.
The syntax for string slicing is s[start:end] or s[start:end:step]. Link to docs