我目前正在使用com进行Excel的Python自动化.它功能齐全,可以满足我的需求,但我发现了一些令人惊讶的东西.有时,我使用的某些Excel命令会因为没有明显原因的异常而失败.其他时候,他们会工作.
在我正在做的VB等效代码中,这个问题显然被认为是正常的,并且用一个On Error Resume Next语句贴满了.当然,Python没有声明.
我无法将整个集合包裹在一个try except循环中,因为它可能会在中途"失败"并且无法正常完成.那么,将几个独立语句包装到try除块之外的pythonic方法是什么?具体来说,比以下更清洁:
try:
statement
except:
pass
try:
statement
except:
pass
Run Code Online (Sandbox Code Playgroud)
相关的代码是excel.Selection.Borders位.
def addGridlines(self, infile, outfile):
"""convert csv to excel, and add gridlines"""
# set constants for excel
xlDiagonalDown = 5
xlDiagonalUp = 6
xlNone = -4142
xlContinuous = 1
xlThin = 2
xlAutomatic = -4105
xlEdgeLeft = 7
xlEdgeTop = 8
xlEdgeBottom = 9
xlEdgeRight = 10
xlInsideVertical = 11
xlInsideHorizontal = 12
# open file
excel = win32com.client.Dispatch('Excel.Application') …Run Code Online (Sandbox Code Playgroud) 当文本文件中的第2行具有"nope"时,它将忽略该行并继续下一行.是否有另一种方法来写这个没有使用尝试,除了?我可以使用if else语句来执行此操作吗?
文本文件示例:
0 1
0 2 nope
1 3
2 5 nope
Run Code Online (Sandbox Code Playgroud)
码:
e = open('e.txt')
alist = []
for line in e:
start = int(line.split()[0])
target = int(line.split()[1])
try:
if line.split()[2] == 'nope':
continue
except IndexError:
alist.append([start, target])
Run Code Online (Sandbox Code Playgroud) 我一直在和朱莉娅一起玩,因为它似乎在语法上类似于python(我喜欢),但声称速度更快.但是,我尝试使用python中的类似脚本来测试数值在使用此函数的文本文件中的位置:
function isFloat(s)
try:
float64(s)
return true
catch:
return false
end
end
Run Code Online (Sandbox Code Playgroud)
出于某种原因,对于具有合理数量的文本行(~500000)的文本文件,这需要花费大量时间.
为什么会这样?有一个更好的方法吗?我可以从中理解该语言的一般特征是否适用于其他语言?
以下是我运行的两个确切脚本以供参考:
python:~0.5秒
def is_number(s):
try:
np.float64(s)
return True
except ValueError:
return False
start = time.time()
file_data = open('SMW100.asc').readlines()
file_data = map(lambda line: line.rstrip('\n').replace(',',' ').split(), file_data)
bools = [(all(map(is_number, x)), x) for x in file_data]
print time.time() - start
Run Code Online (Sandbox Code Playgroud)
朱莉娅:~73.5秒
start = time()
function isFloat(s)
try:
float64(s)
return true
catch:
return false
end
end
x = map(x-> split(replace(x, ",", " ")), open(readlines, "SMW100.asc"))
u = [(all(map(isFloat, i)), …Run Code Online (Sandbox Code Playgroud) python ×2
try-catch ×2
com ×1
excel ×1
file ×1
filter ×1
julia ×1
performance ×1
try-except ×1
vba ×1