我是Python新手。在我的 python 脚本中,我打开一个文件进行读取,并想要处理某些行。我想忽略以“*”或“#”开头的行。这是我的代码:
line = DLF_P.readline()
while line:
if not line.startswith('*') or not line.startswith('#'):
time = line.split()[0]
print time
time = datetime.strptime(time, FMT)
if start < bdoyend:
print time
line = DLF_P.readline()
我收到第一行(包含星号)与格式“HH:MM:SS”不匹配的错误。我认为我的代码会忽略这些类型的行。
ValueError: time data '**' does not match format '%H:%M:%S'
我这样做错了吗?
最佳答案
线路
if not line.startswith('*') or not line.startswith('#'):
应该是
if not line.startswith('*') and not line.startswith('#'):
或
if not (line.startswith('*') or line.startswith('#')):
如果您想忽略以 *
开头的行和以 #
开头的行
关于Python 忽略文件中以以下开头的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45894918/