Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用`with`运算符读取文件时出现问题_Python - Fatal编程技术网

在python中使用`with`运算符读取文件时出现问题

在python中使用`with`运算符读取文件时出现问题,python,Python,我有一个使用with语句逐行读取文件的代码。下面的代码在无限循环中运行,每次都打印第1行。不知道我犯了什么错误 with open (config_file) as fp: line = fp.readline() print("line is", line) while line: match = re.search("^QueueDir\s*=\s*(.*)$", line)

我有一个使用with语句逐行读取文件的代码。下面的代码在无限循环中运行,每次都打印第1行。不知道我犯了什么错误

  with open (config_file) as fp:
        line = fp.readline()
        print("line is", line)
        while line:
            match = re.search("^QueueDir\s*=\s*(.*)$", line)
            if (match.group(1)):
                return match.group(1)

在while循环的末尾添加
line=fp.readline()
。As
不会从一个循环切换到下一个循环

  with open (config_file) as fp:
        line = fp.readline()
        print("line is", line)
        while line:
            match = re.search("^QueueDir\s*=\s*(.*)$", line)
            if (match.group(1)):
                return match.group(1)
            line = fp.readline()

变量
fp
是一个文件句柄,使用
for
循环可以轻松访问循环中的元素

with open (config_file) as fp:
    for line in fp:
        match = re.search("^QueueDir\s*=\s*(.*)$", line)
        if (match.group(1)):
            return match.group(1)

由于while条件,
while line:
,代码进入无限循环,在条件的情况下,任何非零值都被视为
True
,因此
line
是非空的,条件被解释为
while True
,因此它无限运行。

在fp中对line使用
,不是
fp.readline()
。在使用
statement@Akshat不,的默认模式是
'r'
,这在这里很好。
lines=fp.readline()
只读取一行。您的
for
循环最终会迭代其各个字符。您希望fp:
中的行使用简单明了的
。另外,
print
引用了一个未初始化的变量。@tripleee谢谢,我已经编辑了代码。@tripleee
print(“行是”,行)
来自OP的代码,我没有注意到,我的错误。“你的变量是列表”仍然不是真的,但我想你也可以修复它。@tripleee谢谢你指出。