首页 > 解决方案 > 使用 Python 从文本文件中读取数据并放入网格中

问题描述

我有以下数据的文本文件,逐行显示为:

TC1

经过

TC2

失败

TC3

经过

现在我想阅读文本文件并在我的 tkinter 网格中导入为:

行 0 列 0 列 1

第 1 行 Tc1 通行证

第 2 行 TC2 失败

第 3 排 TC3 通行证

我有以下代码 & 只是试图阅读以 T 开头的单词 & 将其放在网格中:

打开(文本文件)作为打开文件:

    for line in openfile:
        for part in line.split():
            i=0
            if line.startswith('T'):
                print line
                i=i+1
                Label(labelone,text=part,relief=RIDGE,width=16).grid(row=i,column=1)

当我在上面运行时,它给出:

行 0 列 0 列 1

第 1 行 TC3

第 2 行

第 3 行

任何帮助,将不胜感激。谢谢

标签: pythontexttkinter

解决方案


这里有几件事需要注意。

1) 处理文件中的空行.txt

2)迭代以得到一个耦合的结果,就像TC1 Pass在一起。

3) 将耦合对向后追加/插入到网格中。

方法:

制作一个包含.txt文件中所有数据的列表,然后迭代以获取稍后可以插入到网格中的配对结果。

logFile = "list.txt"

with open(logFile) as f:
    content = f.readlines()

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]

# flag
nextLine = False

# list to save the lines
textList = []

for line in content:
    find_TC = line.find('TC')

    if find_TC > 0:
        nextLine = not nextLine
    else:
        if nextLine:
            pass
        else:
            textList.append(line)

print('\n')
print('Text list ..')
print(textList)

j = 0
for i in range(j, len(textList)):
    if j < len(textList):
        print(textList[j], textList[j + 1]) # Insert into the gird here instead of print
        j = j + 2

输出:

文字列表..

['TC1','通过','TC2','失败','TC3','通过']

TC1 通行证

TC2 失败

TC3 通行证

编辑:

OP对文本文件的新更改之后

j = 0
for i in range(j, len(textList)):
    if j < len(textList):
        print(textList[j], textList[j + 1], textList[j+2]) # Insert into the gird here instead of print
        j = j + 3

推荐阅读