Reputation: 13
I am learning Python from scratch in the sense that I do not have much coding background. In this particular exercise, I am given the task of taking a text file, removing the spaces and commas, then printing it out as seven individual lines (which I have done.) Now, that I finished the task, I need to display real, incrementing time before the individual int on each line, while also adding a day to the line reading 'blank blank.'
I've tried several approaches and cannot seem to get both criteria to occur simultaneously. Here is the code I have written:
from datetime import datetime
from datetime import timedelta
with open("C:\Users\curnutte\Desktop\Assignment\Python Scripts\Python example\RandomFile.txt", "r") as inp:
with open("C:\Users\curnutte\Desktop\Assignment\Python Scripts\Python example\RandomFileOutput.txt", "w") as outp:
clock = datetime.now()
for line in inp.readlines():
total = 0
line = line.strip()
parts = line.split(",")
for part in parts:
try:
num = int(part)
total += num
except ValueError:
total = (" ".join(parts))
break
#for line in inp:
if total == int:
total_time = clock + timedelta(seconds = 1)
print (clock + timedelta (seconds = 1))
else:
total_time = clock + timedelta(days = 1)
print (clock + timedelta (days = 1))
outp.write("%s: " % total_time)
outp.write('{}\n'.format(total))
And here is 'RandomFile:'
1,2
2,3
3,4
4,5
blank,blank
5,6
6,7
With the code I have provided, here is the 'RandomFileOutput' that I receive:
2016-06-28 13:47:56.106000: 13
Up until I added the last if, else statement I was receiving the output of:
2016-06-28 13:51:19.709000: 3
2016-06-28 13:51:19.709000: 5
2016-06-28 13:51:19.709000: 7
2016-06-28 13:51:19.709000: 9
2016-06-28 13:51:19.709000: blank blank
2016-06-28 13:51:19.709000: 11
2016-06-28 13:51:19.709000: 13
Can anybody shed some light on what I've done wrong?
Upvotes: 0
Views: 69
Reputation: 3785
I think your indentation is wrong, and you should be checking for the type of the total, not total==int:
from datetime import datetime
from datetime import timedelta
with open("RandomFile.txt", "r") as inp:
with open("RandomFileOutput.txt", "w") as outp:
clock = datetime.now()
for i, line in enumerate(inp.readlines()):
total = 0
line = line.strip()
# print(line)
parts = line.split(",")
for part in parts:
try:
num = int(part)
total += num
except ValueError:
total = (" ".join(parts))
break
#for line in inp:
print(type(total))
if type(total) == int:
total_time = clock + timedelta(seconds = 1)
print (clock + timedelta(seconds = 1))
else:
total_time = clock + timedelta(days = 1)
print (clock + timedelta(days = 1))
outp.write("%s: " % total_time)
outp.write('{}\n'.format(total))
prints:
<class 'int'>
2016-06-28 16:12:11.967791
<class 'int'>
2016-06-28 16:12:11.967791
<class 'int'>
2016-06-28 16:12:11.967791
<class 'int'>
2016-06-28 16:12:11.967791
<class 'str'>
2016-06-29 16:12:10.967791
<class 'int'>
2016-06-28 16:12:11.967791
<class 'int'>
2016-06-28 16:12:11.967791
Upvotes: 1