我是python的新手,所以我有点混淆如何处理它。
我试图将项目附加到列表中:
li = []
for path, subdirs, files in os.walk('/data/disk4/a0050969/sftpcollector/Utils/'):
for filename in files:
if filename.endswith(('.log')):
f = os.path.join(path, filename)
li.append(f)
print f
它让我:
[] [' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0325pl/secondftp_20160608.log'] [' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0325pl/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0324pl/secondftp_20160608.log'] [' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0325pl/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0324pl/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondother_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondhttp_20160608.log']
我只是期待:
[' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0325pl/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0324pl/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondftp_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondother_20160608.log' ;, ' /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondhttp_20160608.log']
另一方面,如果我这样做:
with open(LOCAL_F_PATH_CTRL+'temp.tmp', "w") as dd:
for path, subdirs, files in os.walk('/data/disk4/a0050969/sftpcollector/Utils/'):
for filename in files:
if filename.endswith(('.log')):
f = os.path.join(path, filename)
dd.write(str(f)+os.linesep)
它写下了我需要的方式:
/data/disk4/a0050969/sftpcollector/Utils/brtlvlts0325pl/secondftp_20160608.log /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0324pl/secondftp_20160608.log /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondftp_20160608.log /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondother_20160608.log /data/disk4/a0050969/sftpcollector/Utils/brtlvlts0264co/secondhttp_20160608.log
我无法弄清楚代码的错误。
答案 0 :(得分:0)
Python非常重视缩进,因此在代码的第一个示例中,因为
f = os.path.join(path, filename)
li.append(f)
符合if
条件,代码块只运行一次而不是循环。如果它在循环中,如第二个例子所示,它会将它正确地附加到列表中
答案 1 :(得分:0)
当您发布代码时,可能只是格式化错误,但下面的行没有在if语句下正确缩进。这可能是你的问题。
f = os.path.join(path, filename)
li.append(f)
答案 2 :(得分:0)
您的第一个代码段中的缩进肯定是错误的。在if
之后,至少在线需要缩进。
您是否在代码中混合制表符和空格?这有时会很难检测到错误。我建议您将编辑器配置为在点击Tab
键时自动插入空格。