检查回车是否在给定字符串中

2024-04-23 17:54:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一个文件中读取一些行,我正在检查每一行是否有windows类型的CRLF。如果任何行中都没有'\n'或'\r',则必须报告错误。我尝试使用下面的代码,即使该行没有'\r',它也不会报告任何错误

Open_file = open(File_Name,'r').readlines()
while Loop_Counter!= Last_Line:
        Line_Read = Open_file[Loop_Counter]
        if('\r\n' in Line_Read):
            pass
        else:
            print Loop_Counter

谢谢你


Tags: 文件代码loop类型readwindows报告错误
3条回答

试试这个

Open_file = open(File_Name,'rb').readlines()

必须以二进制模式打开文件

应该是的

if ('\r' not in Line_Read or '\n' not in Line_Read): 
    print Loop_Counter

?? 而且,正如jdotjdot指出的,循环计数器根本没有递增。

这不起作用,因为Loop_Counter根本没有调整;无论初始值是什么,它都不会改变,while循环要么无限期运行,要么永远不会通过。你的代码在这里很不清楚;我不知道你为什么要这样构造它。

你的建议更容易做到:

infile = open(filename, 'rb')
for index, line in enumerate(infile.readlines()):
    if line[-2:] != '\r\n':
        print index

必须使用'rb'参数来确保新行被读取为\r\n,而不仅仅是\n

相关问题 更多 >