我是从零开始学习Python的,因为我没有太多的编码背景。在这个特殊的练习中,我的任务是获取一个文本文件,删除空格和逗号,然后将其打印为七行(我已经这样做了)。现在,我完成了任务,我需要在每行上的单个int之前显示实际的、递增的时间,同时还向读取'blank blank '的行添加一天。'
我尝试了几种方法,但似乎无法同时得到两个标准。下面是我写的代码:
from datetime import datetime
from datetime import timedelta
with open("C:UserscurnutteDesktopAssignmentPython ScriptsPython exampleRandomFile.txt", "r") as inp:
with open("C:UserscurnutteDesktopAssignmentPython ScriptsPython exampleRandomFileOutput.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
谁能告诉我我做错了什么? 我认为你的缩进是错误的,你应该检查total的类型,而不是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))
打印:
<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