目前,我只想弄清楚为什么这段代码不起作用。
编辑:写了一些新代码
编辑2:已解决(阅读评论提醒我编码with.open()所以现在看起来像这样,
编辑3:用于拉出两个单词之间需要的“字符串”(日期)的新代码。
import os
items=os.listdir("C:/output")
for names in items:
if names.endswith(".txt"):
with open('C:/output/' + names, encoding="utf8") as currentFile:
text = currentFile.read()
if ('Date Released' in text):
a = 'Released'
b = 'Description'
startpos = text.find(a) + len(a)
endpos = text.find(b, startpos)
print('Date Released ' + text[startpos:endpos] + names + '\n')
#print ('Found in ' + names[:-4] + '\n')
else:
print ('Not in ' + names[:-4] + '\n')
我现在得到输出:
Date Released : 12/14/2016
1393-004IP_ B_ C2 filename
Date Released : 4/11/2017
1476-002 IP, filename
Date Released : 9/25/2015
1987-XXX IP filename
有没有办法让Date发布:#/ ## / ####行与文件名在同一行?此外,我现在运行时得到的一些输出是垃圾。我假设它可能来自检查发布日期不止一次或可能存在if条件的缺陷?
答案 0 :(得分:0)
如果您正在使用Windows,请尝试使用double" \"而不是单一" /"在路径名称