我在运行SyntaxError: EOL while scanning string literal
时遇到timeit.Timer
错误。我的设置是一个跨越多行的长字符串:
setup = """
import datetime
import glob
import os
import pandas as pd
ydate = str(20180308)
# Import
path = 'path_to_file'
all_files = glob.glob(os.path.join(path, '*.csv'))
all_files = [x for x in all_files if ydate in x]
all_files = [x.replace('\\','/') for x in all_files]"""
我已经移动了引号,尝试在'
和"
位置进行交换,我能想到的任何东西通常会修复此错误,但是当我运行时它仍会抛出错误< / p>
t = timeit.Timer("[pd.read_csv(x,encoding='latin-1') for x in all_files]", setup=setup)
t.timeit()
也可以采用不同的方式来计算时间。我基本上比较了map
与列表理解解决方案的时间。
答案 0 :(得分:1)
SyntaxError出现在设置的最后一行。一种解决方案是在最后一行添加一对反斜杠:
setup = """
import datetime
import glob
import os
import pandas as pd
ydate = str(20180308)
# Import
path = 'path_to_file'
all_files = glob.glob(os.path.join(path, '*.csv'))
all_files = [x for x in all_files if ydate in x]
all_files = [x.replace('\\\\', '/') for x in all_files]"""
但是,glob
应返回操作系统的有效路径。因此,如果您使用正斜杠替换反斜杠,则您的操作系统可能无法再找到这些文件。在这种情况下,我建议您跳过设置的最后一行:
setup = """
import datetime
import glob
import os
import pandas as pd
ydate = str(20180308)
# Import
path = 'path_to_file'
all_files = glob.glob(os.path.join(path, '*.csv'))
all_files = [x for x in all_files if ydate in x]"""