如果您有一个名为 parameters.txt 的文件,其中包含数据
foo
bar
foobar
还有一个函数
def my_function(some_text):
print("I was called with " + some_text)
然后你可以这样做将文件的每一行传递给函数:
with open('parameters.txt', 'r') as my_file:
for line in my_file:
# remove the # and space from the next line to enable output to console:
# print(line.rstrip())
my_function(line.rstrip())
请注意,我所有示例中的 rstrip() 方法都会去除尾随换行符(以及其他尾随空格),否则它们会成为每行的一部分。
如果你的参数文件有一个标题,就像你的例子一样,你有多种可能跳过它。
例如,您可以一次将所有行读入一个列表,然后遍历一个子集:
with open('parameters.txt', 'r') as my_file:
all_lines = [line.rstrip() for line in my_file.readlines()]
# print(all_lines)
for line in all_lines[1:]:
# print(line)
my_function(line)
但是,这只会忽略标题。如果您不小心传递了错误的文件或包含无效内容的文件,这可能会带来麻烦。
最好检查一下文件头是否正确。您可以从上面展开代码:
with open('parameters.txt', 'r') as my_file:
all_lines = [line.rstrip() for line in my_file.readlines()]
# print(all_lines)
if all_lines[0] != 'COM_PORTS':
raise RuntimeError("file has wrong header")
for line in all_lines[1:]:
# print(line)
my_function(line)
或者您可以在循环中执行此操作,例如:
expect_header = True
with open('parameters.txt', 'r') as my_file:
for line in my_file:
stripped = line.rstrip()
if expect_header:
if stripped != 'COM_PORTS':
raise RuntimeError("header of file is wrong")
expect_header = False
continue
# print(stripped)
my_function(stripped)
或者您可以使用生成器表达式来检查循环外的标头:
with open('parameters.txt', 'r') as my_file:
all_lines = (line.rstrip() for line in my_file.readlines())
if next(all_lines) != 'COM_PORTS':
raise RuntimeError("file has wrong header")
for line in all_lines:
# print(line)
my_function(line)
我可能更喜欢最后一个,因为它结构清晰,没有神奇的数字(例如0 和1,分别指哪一行是标题以及要跳过多少行),而且它不需要一次将所有行读入内存。
但是,如果您想对它们进行进一步处理,那么上述将所有行一次读入列表的解决方案可能会更好,因为在这种情况下数据已经可用并且您不需要再次读取文件.