我有一个循环遍历文件的函数,如下所示:
"#" XDI/1.0 XDAC/1.4 Athena/0.9.25
"#" Column.4: pre_edge
Content
也就是“#”后面有注释。我的函数旨在读取每一行,如果它以特定单词开头,则选择“:”之后的内容
例如,如果我有这两行。我想通读它们,如果该行以“#”开头并包含单词“Column.4”,则应存储单词“pre_edge”。
我当前方法的示例如下:
with open(file, "r") as f:
for line in f:
if line.startswith ('#'):
word = line.split(" Column.4:")[1]
else:
print("n")
我认为我的问题是在找到以“#”开头的行之后,我该如何解析/搜索它?如果它包含所需的词,则保存其内容。
最佳答案
如果 #
注释包含 str Column.4:
如上所述,您可以这样解析它。
with open(filepath) as f:
for line in f:
if line.startswith('#'):
# Here you proceed comment lines
if 'Column.4' in line:
first, remainder = line.split('Column.4: ')
# Remainder contains everything after '# Column.4: '
# So if you want to get first word ->
word = remainder.split()[0]
else:
# Here you can proceed lines that are not comments
pass
注意事项
此外,使用 for line in f:
语句而不是 f.readlines()
(如其他答案中所述)也是一个好习惯,因为这样你不要将所有行都加载到内存中,而是一条一条地执行。
关于python - 如何在python中打开文件,阅读注释 ("#"), 找到注释后面的单词并选择它后面的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54449176/