简体   繁体   English

python [regex] - 搜索 function 在从文件中读取行时不起作用

[英]python [regex] - search function is not working while reading lines from a file

I have written the following python section code in order to open a file and read it line by line and detect if a line is starting by a letter or number.我编写了以下 python 部分代码,以便打开文件并逐行读取并检测一行是否以字母或数字开头。

For some strange reason, the search() function is not working correct as a result we never enters the if statement.由于某些奇怪的原因, search() function 无法正常工作,因此我们从未输入if语句。 My code is below:我的代码如下:

import re

path = "path/to/my/file/data.txt" 

with open(path, 'r') as f:
    line = f.read()
    if (re.search("^[a-zA-Z0-9]", line)):
        print "YES"

If you want to read the file line by line, you need to iterate over it, like this, f.read() will just load the entire file as a string, so your if will only be reached once for all data.如果要逐行读取文件,则需要对其进行迭代,就像这样, f.read()只会将整个文件作为字符串加载,因此对于所有数据,您的if只会到达一次。 If it doesn't start with an alphanumerical, you won't reach your print .如果它不以字母数字开头,您将无法访问您的print

To iterate over it, you can do that with要对其进行迭代,您可以使用

with open(path, 'r') as f:
    for line in f:
        if (re.search("^[a-zA-Z0-9]", line)):
            print("YES")

To iterate over the file line by line逐行遍历文件

import re

path = "path/to/my/file/data.txt" 

with open(path, 'r') as f:
    for line in f:       # iterating over the file object line by line
        if (re.search("^[a-zA-Z0-9]", line)):
            print "YES"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM