【问题标题】:What's wrong with this Python file-read test?这个 Python 文件读取测试有什么问题?
【发布时间】:2010-12-24 21:42:32
【问题描述】:

这个 Python 文件读取测试有什么问题?

import os
import sys

fileList = os.listdir(sys.argv[1])
count = 0
for file in fileList:
    try:
        count += 1
        print os.path.isfile(file)
        if os.path.isfile(file)
            print "File >> " + file
        else
            print "Dir >> " + file
    except err:
        print "ERROR: " + err
        print ">> in file: " + file

给予:

文件“test.py”,第 10 行 如果 os.path.isfile(file) ^ SyntaxError: 无效语法

为什么?

【问题讨论】:

  • 另外,enumerate
  • @delnan 我在做什么有什么不同?
  • enumerate 函数返回一个枚举器对象,它是格式为 (index, object) 的元组列表,因此list(enumerate(["a", "b"])) 返回[(0, 'a'), (1, 'b')]。所以你需要使用 count 变量。你可以使用for count, file in enumerate(fileList):
  • @None 看起来比我刚刚做的更复杂。实际上,如果你在谈论,那么它一定会更好,但我不明白它在哪个方面更好..
  • 更好的是它少了两行并且与continue 很好地配合。这也是使用现有解决方案而不是自己做的问题。这个“更复杂”是怎么回事?

标签: python file file-io


【解决方案1】:

if 和 else 行缺少冒号

if (something):   #note the : at the end
  ...
else:
  ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2011-09-15
    • 1970-01-01
    • 2013-09-13
    • 2010-11-30
    • 2019-01-30
    • 2013-02-17
    相关资源
    最近更新 更多