python - SyntaxError:with 语句套件中的语法无效
问题描述
我正在运行tweak_starfile.py,它从CSV 文件中读取有关附近恒星的数据,并将数据处理成适合我正在开发的明星交易者类型游戏的形式。我在 IDLE 中运行程序。根据良好实践,我将“按摩”代码放在 with 语句中。然而,在 with 套件中,会f.close()
生成一个SyntaxError
. 我究竟做错了什么?据我所知,语法是正确的。
#!/usr/bin/env python3
# file: tweak_starfile.py
# author: Rick Darwin (c) 2018,2019,2020
import math
import re
import pickle
from collections import namedtuple
RAdpar = namedtuple("RAdpar", "RA2k dec parallax")
Polar3 = namedtuple("Polar3", "theta phi rho")
Vectsm = namedtuple("Vectsm", "sec_per_year motion_angle")
Rect3 = namedtuple("Rect3", "x y z")
Stella = namedtuple("Stella", "nomen idcodes spectral colour abs_mag est_mass num_obj rect3 note")
def tweak_starfile(starcount, csvfile='RECONSNearest110.csv', starfile='starfile_001.dat'):
""" Read one line from csvfile, unpack to a tuple, massage the data,
append a new Stella() namedtuple to list starcat. Repeat till starcount
records are done, then pickle the resultant starcat.
"""
with open(csvfile, 'r') as f:
starcat = []
linect = 0
for line in f.readlines():
if linect == 0:
pass # ignore the column heads
else:
if linect >= starcount:
print('{} records read from {}. '.format(linect, csvfile)) #DEBUG
break
#. end if
# Read in the data
# Massage the data
# Make a new tuple
#. Save the record to the catalog
#. end for
f.close() # *** SyntaxError: invalid syntax ***
#. end with
# Write out the data
print('Writing out the data to ./starfile')
with open(starfile, 'wb') as f:
pickle.dumps(starcat, f, protocol=pickle.HIGHEST_PROTOCOL)
f.close()
#. end with
#. end def
def hms2hhhh(hms):
""" Convert a hms string like '20:30:40.1' or '06 45 08.9' into decimal hours
(without ValueError on 09 or 08.9, (ie, not treated as oct!)
"""
suite
#. end def
def hhh2rad(hhh):
""" Convert decimal hours to radians
"""
suite
#. end def
def starcolour(spectra):
""" Return a 3tuple from a color picker; spectral holds a string like 'M5.0 V'
"""
print('In starcolour')
sc = spectra[0]
dicto = {
'O': (0, 153, 255), # blue
'B': (102, 204, 255), # blue-white
'A': (255, 255, 255), # white
'F': (255, 255, 153), # yellow-white
'G': (255, 255, 0), # yellow
'K': (255, 153, 0), # orange
'M': (192, 51, 0), # red
'D': (255, 0, 0) # deep red
}
return dicto[sc] if sc in dicto.keys() else (0, 255, 255) # cyan! why not?
#. end def
if __name__ == '__main__':
tweak_starfile(110, "RECONSNearest110.csv", "starfile_001.dat")
解决方案
推荐阅读
- beautifulsoup - Beautifulsoup 抓取对象选择
- ubuntu - 通过 VPS 中的端口使用 OpenVPN Server
- reactjs - 如何使用 Rest Framework 从前端(React)向 Django 发送查询
- iis - 如何轻松启用/禁用 IIS 中的所有模块?
- html - 错误 TS2322:类型“事件”不可分配给类型“布尔”
- javascript - 未处理的拒绝 TypeError: Role.Create is not a function 错误
- google-cloud-platform - 从不再打开的 VM 实例下载 jupyter notebook
- python - 我在我的块中添加了一行代码,虽然我得到的答案是正确的,但我不明白那条简单的行是做什么的
- docker - 在 docker-compose 中为 influxdb 2.0 创建默认用户
- python - 使用 plt.plot 后不出现绘图