繁体   English   中英

打开和打印 txt 文件时出现“IndexError: list index out of range”

[英]"IndexError: list index out of range" when opening and printing a txt file

我正在大学学习编程基础知识 class。 对于作业,我必须在 Python 中打开一个 txt 文件,并将其中的元素打印在一种表格中。 txt 文件是客户名称及其 ID 和其他一些信息的列表。 该文件的布局如下:

C1, 詹姆斯, 0, 100

C2, 百合, 0, 30

共有 7 行客户信息。

这是我目前拥有的代码:

file = open('customers.txt', "r")
    content = file.readline()
    while content:
        content = content.split(',')
        sys.stdout.write('{:<4}{:>12}{:>18}{:>9}'.format(content[0],content[1],content[2],content[3],"\n"))
        content = file.readline()
    file.close

它根据需要打印客户信息,但在打印所有客户后出现此错误:

    sys.stdout.write('{:<4}{:>12}{:>18}{:>9}'.format(content[0],content[1],content[2],content[3],"\n"))
IndexError: list index out of range

我不确定如何停止此错误。 我是否需要告诉 Python 有 7 行信息要打印? 如果我正在导入一个文件并且不知道会有多少行信息怎么办?

我还必须将此信息添加到 Python 中的列表中,我目前没有这样做,但这是一个单独的问题。

任何帮助将不胜感激:)

只需添加它以表明您可以根据需要简化一些逻辑。 例如,使用print和 f-strings 而不是格式字符串。

file_contents = """\
C1, James, 0, 100
C2, Lily, 0, 30
"""

for line in file_contents.strip().split('\n'):
    content = line.split(',')
    print(f'{content[0]:<4}{content[1]:>12}{content[2]:>18}{content[3]:>9}')

暂无
暂无

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

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