【问题标题】:Syntax Error while iterating through list [closed]遍历列表时出现语法错误[关闭]
【发布时间】:2014-07-11 22:09:48
【问题描述】:

我根据合同编写了一个程序,该程序可以打开文件夹中的文件,将新行添加到列表中并检查重复项(通过每次从一组原始列表 (file_contents) 中创建一个列表来完成添加了新条目)。

sort() 方法的目的是打开列表 full_file_paths 中包含的所有文件并将其内容存储在列表中。但是,我收到一个错误(如下):

File "line_sort.py", line 24
  for entry in L:
                ^
SyntaxError: invalid syntax

有问题的方法如下:

def sort(directory):
    full_file_paths = get_filepaths(directory)
    # Go file by file
    for path in full_file_paths:
        with open(path, "r") as current_file:
            L = current_file.read().splitlines()
            print (str("Reading " + path)
            for entry in L:
                file_contents.append(entry.strip())
        # Creates a set from the array, which cannot contain duplicates.
        file_contents = list(set(file_contents))

我尝试更改数组的名称以考虑保留字,并且我尝试在不打开文件的情况下遍历列表并且它可以工作。
导致错误的行是此方法底部的第 4 行。我将在接下来的时间里摆弄这个,同时希望能抓住这个问题。

感谢您的宝贵时间!

【问题讨论】:

    标签: python sorting csv


    【解决方案1】:

    你还没有关闭上一行的括号:

    print (str("Reading " + path))
                                 ^
    

    仅供参考,您根本不需要调用str(),因为看起来path 也是str 类型:

    print("Reading " + path)
    

    【讨论】:

    • 看那个。该程序正是我现在想要的。对于浪费时间,我深表歉意。
    【解决方案2】:

    正如@alecxe 所说,您忘记了括号...但我宁愿说您忘记了避免括号:

    print (str("Reading " + path))
          ^                      ^
    

    这些括号没有用,因为 print 是一个 语句 而不是 函数(请参阅 the doc)。正如@Fred 指出的那样,这适用于python 版本

    此外,我们在这里看不到 get_filepaths 函数,但如果您不确定返回的可迭代路径集是字符串,则应仅包装 path 变量。所以你可以简单地写:

    print "Reading " + str(path)
    

    【讨论】:

    • 除非这是 Python 3。
    • @FredLarson,好点
    • 我确实忘记了括号。而且我使用的是 3.3.2 版本,所以我确实需要 print 函数中的括号。
    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 2017-11-24
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多