使用Python2.7从文本文件中读取特定行并将其赋值给变量

2024-05-23 23:17:56 发布

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

我想在一个文本文件中自动搜索3行文本,然后在python脚本中将其指定为变量。这个过程基本上包括tkinter提示用户选择文本文件,然后这三行被定位到文本文件中并被指定为变量。所需的三行文本将始终位于文本文件中的同一位置(例如,它将始终是第10、11和12行)。下面是我能做的,但是这只打印整个文本文件。在

#set bounds
bounds=tkFileDialog.askopenfile(title='Select bounds text file:',filetypes=[("Text files","*.txt")])

rbounds=bounds.readlines()
for line in rbounds:
    print line

最后的print语句是查看运行脚本后的结果。 如何拆分或切片文本文件中的行,然后将其分配给变量?在


Tags: 用户定位文本脚本tkinter过程line中将
1条回答
网友
1楼 · 发布于 2024-05-23 23:17:56

您可以使用slice语法来获取子列表。请记住,在Python中,列表是0索引的。在

rbounds = bounds.readlines()
lines_with_data = rbounds[9:12]    # gives lines 9-11, given first line is 0th
for l in lines_with_data:
    pass  # parse_line here

相关问题 更多 >