简体   繁体   English

将文本中的数字读入 python 中的变量

[英]reading numbers from text into variables in python

assume i have a text file that only has the following format where each line has two numbers separated by a space:假设我有一个仅具有以下格式的文本文件,其中每行有两个由空格分隔的数字:

2 4
66 99
11 67
1 3 

this is my code which i tried doing:这是我尝试做的代码:

with open('text_file.txt') as file:
    lines = []
    for i in file:
        lines.append(i)
    print(lines)

the problem with my code is that it keeps printing "\n" with the numbers and i don't know how to get around that i need a way to read only the two numbers in the last line and store each number in a variable, so for the example above:我的代码的问题是它一直用数字打印“\ n”,我不知道如何解决我需要一种方法来只读取最后一行中的两个数字并将每个数字存储在一个变量中,所以对于上面的例子:

var1 = 1 , var2 = 3 . var1 = 1var2 = 3

i need this for a multi-threading program, where i am testing a "race condition" between three threads where each thread reads the last two numbers in the text file and read the last line of numbers, and then print the thread_ip in the first,and increment the second from the previous last line and print it.我需要这个用于多线程程序,我正在测试三个线程之间的“竞争条件”,其中每个线程读取文本文件中的最后两个数字并读取最后一行数字,然后在第一个中打印 thread_ip , 并从前最后一行增加第二个并打印它。

im not asking for help for the whole assignment, just the reading/writing the text file part is what i can't seem to figure out.我没有为整个作业寻求帮助,只是读/写文本文件部分是我似乎无法弄清楚的。

with open("example_file", "r") as fin:
   var1, var2 = [int(i) for i in fin.readline().split()]

To store the last two numbers in the last line:要将最后两个数字存储在最后一行:

with open("example_file", "r") as fin:
   var1, var2 = [int(i) for i in fin.readlines()[-1].split()]

So both of the examples in the currently accepted answer from izhang work, but they come with a cost... In the first example, you have to needlessly walk the entire file to come to the last line.因此,zhang 目前接受的答案中的两个示例都有效,但它们都需要付出代价……在第一个示例中,您必须不必要地遍历整个文件才能到达最后一行。 And in the second example, you have to read the entire file into memory.在第二个示例中,您必须将整个文件读入 memory。 If dealing with large datasets, and/or running inside of constrained containers, this will absolutely become a problem.如果处理大型数据集,和/或在受限容器内运行,这绝对会成为一个问题。

The better solution is to read the file backwards and break after the first read line.更好的解决方案是向后读取文件并在第一行读取后中断。 This is not an easy task to do from scratch, but fortunately, there is a module for that.从头开始这不是一件容易的事,但幸运的是,有一个模块可以做到这一点。

from file_read_backwards import FileReadBackwards

with FileReadBackwards('text_file.txt') as f:
    for l in f:
        var1, var2 = l.split()
        break
print(var1, var2)

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

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