Python 遍历列表时出现语法错误
根据合同,我将编写一个程序,打开文件夹中的文件,将新行添加到列表中,并检查重复项(通过每次添加新条目时从一组原始列表(文件内容)中创建列表来完成) sort()方法的目的是打开列表完整文件路径中包含的所有文件,并将其内容存储在列表中。但是,我收到一个错误(如下所示): 有关方法如下:Python 遍历列表时出现语法错误,python,sorting,csv,Python,Sorting,Csv,根据合同,我将编写一个程序,打开文件夹中的文件,将新行添加到列表中,并检查重复项(通过每次添加新条目时从一组原始列表(文件内容)中创建列表来完成) sort()方法的目的是打开列表完整文件路径中包含的所有文件,并将其内容存储在列表中。但是,我收到一个错误(如下所示): 有关方法如下: def sort(directory): full_file_paths = get_filepaths(directory) # Go file by file for path in f
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行。我将在接下来的时间里处理这个问题,同时希望抓住这个问题
谢谢你抽出时间 您还没有关闭前一行的括号:
print (str("Reading " + path))
^
仅供参考,您根本不需要调用str()
,因为它看起来像path
也是str
类型:
print("Reading " + path)
正如@alecxe所说,您忘记了一个括号。。。但我宁愿说你忘了避开括号:
print (str("Reading " + path))
^ ^
这些括号是无用的,因为print是语句而不是函数(请参阅)。正如@Fred指出的,这适用于<3的python版本
此外,我们在这里没有看到get\u filepaths
函数,但是如果您不确定返回的iterable路径集是否是字符串,则应该只包装path变量。所以你可以简单地写:
print "Reading " + str(path)
看那个。这个程序正是我现在想要的。我为浪费时间道歉。除非这是Python 3。@Fredrarson,说得好,我确实忘记了括号。我使用的是3.3.2版,所以打印函数中需要括号。
print "Reading " + str(path)