python - 使用 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 行
任何帮助,将不胜感激。谢谢
解决方案
这里有几件事需要注意。
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
推荐阅读
- mysql - 在没有 CTE 的情况下删除 MySql 中的多行
- python - 如何中断线程定时器?
- amazon-web-services - Amazon SQS FIFO 队列 - 总共获得 10 条消息,但仍强制执行 MessageGroupId 计数?
- javascript - 使用jquery获取输入字段的值
- angular - 无法将节点模块添加到 Angular 项目
- python - 如何为 Sportmonks 获取 api_token?
- python - 从文件夹中的所有视频中获取视频帧,使用 openCV 处理,保存到自己的文件夹?
- git - 通过命令行以编程方式设置 git 凭据缓存
- python - 类型错误:预测()缺少 1 个必需的位置参数:'X'
- python - "Error while extracting" from tensorflow datasets