Python3:读取文件列表索引超出范围时发生错误

时间:2019-06-10 05:42:39

标签: python python-3.x readfile

我正在尝试读取文件并执行写入其中的命令。我在检查新行时收到错误Error occured while reading file list index out of range

这是代码:

def read_file(self, given_file):
    if not path.exists(given_file):
        print("The mentioned file %s does not exist" % given_file)

    with open(given_file, 'r+') as file_obj:
        try:
            while True:
                line = file_obj.readline()
                print(line)
                if line.endswith('\n'):
                    line = line[:-1]
                if line == '':
                    continue
                self.read_command(line)
        except StopIteration:
            file_obj.close()
        except Exception as ex:
            print("Error occured while reading file %s" % ex)

以下是输出:

create_parking_lot 6

Created a parking lot with 6 slots


park KA-01-HH-1234 White

Allocated slot number: 1


park KA-01-HH-9999 White

Allocated slot number: 2


park KA-01-BB-0001 Black

Allocated slot number: 3


park KA-01-HH-7777 Red

Allocated slot number: 4


park KA-01-HH-2701 Blue

Allocated slot number: 5


park KA-01-HH-3141 Black

Allocated slot number: 6


leave 4

Slot number 4 is free


status

Slot No.    Registration No.    Color
1       KA-01-HH-1234       White
2       KA-01-HH-9999       White
3       KA-01-BB-0001       Black
5       KA-01-HH-2701       Blue
6       KA-01-HH-3141       Black


park KA-01-P-333 White

Allocated slot number: 4


park DL-12-AA-9999 White

Error occured while reading file list index out of range

我的代码有什么问题,我该如何解决?

2 个答案:

答案 0 :(得分:1)

def read_file(self, given_file):
    if not path.exists(given_file):
        print("The mentioned file %s does not exist" % given_file)

    with open(given_file, 'r+') as file_obj:
        try:
            for line in file_obj:
                print(line)
                if line=="":
                    continue
                elif line.endswith('\n'):
                    line = line[:-1]

                self.read_command(line)
        except StopIteration:
            file_obj.close()
        except Exception as ex:
            print("Error occured while reading file %s" % ex)

您可以尝试这样。可能行得通。

答案 1 :(得分:-1)

尝试一下,它将起作用。您的循环将需要一些更改:

def read_file(self, given_file):
    if not path.exists(given_file):
        print("The mentioned file %s does not exist" % given_file)

    with open(given_file, 'r+') as file_obj:
        line = file_obj.readline()
        try:
            while line:

                print(line)
                if line.endswith('\n'):
                    line = line[:-1]
                if line == '':
                    continue
                self.read_command(line)
                line = file_obj.readline()
        except StopIteration:
            file_obj.close()
        except Exception as ex:
            print("Error occured while reading file %s" % ex)