我从头开始学习Python,因为我没有太多的编码背景。在这个特定的练习中,我的任务是获取一个文本文件,删除空格和逗号,然后将其打印为七条单独的行(我已经完成了)。现在,我完成了任务,我需要显示真实,在每行上的单个int之前增加时间,同时还在读取空行空白的行中添加一天。'
我尝试了几种方法,似乎无法同时发生这两个标准。这是我写的代码:
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))
这是' RandomFile:'
1,2
2,3
3,4
4,5
blank,blank
5,6
6,7
使用我提供的代码,这里是' RandomFileOutput'我收到了:
2016-06-28 13:47:56.106000:13
直到我添加了最后一个if,else语句,我收到了输出:
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
有人能说清楚我做错了什么吗?
答案 0 :(得分:1)
我认为你的缩进是错的,你应该检查总数的类型,而不是总数== 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))
打印:
<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