简体   繁体   中英

Putting integers into a list from a text file

I have a text file and I need to put the numbers in this file into a list like this: [[123,456],[234,567],[345,678]...] but I don't know how to do this as I ran into some error messages shown below.

My text file looks something like this (the --> are arrows in the original text file, but I don't know what they look like if I read the file using with open :

# These are the ids for blablabla
# put the ids into a list like this [[123,456],[234,567],[345,678]...]
#id1 --> id2
#123 --> 456
#234 --> 567
#345 --> 678
#456 --> 789

What I tried to do initially was

with open('mytxt.txt', 'r') as f:
    for line in range(3):
        next(f)
    for line in f:
        lst = list(map(int,line.split(',')))
        print(lst)[:10]

After running this, I got an error message <:-- language: lang-js --> invalid literal for int() with base 10: '123\t456\n' so I thought about stripping the '\n' and the 't' at the end of each line by running the following code:

with open('ca-GrQc.txt', 'r') as f:
    for line in range(4):
        next(f)
    for line in f:
        lst = list(map(int,line.strip('\n').strip('t').split(',')))
        print(lst)[:10]

After running that I still got an error message invalid literal for int() with base 10: '123\t456' which I have no idea where the 't' comes from (and I am sure that 't' was not in the orginal file).

Does anyone know why that happens and how to solve it, or is there a more efficient way of putting the numbers from the text file into a list?

You can use regex to achieve your expected output.

import re
file1 = open("names_file.txt", "r")
l = file1.readlines()
new_list = []
for i in l:
    m = re.findall(r'\d+', i)
    new_list.append(m)
print(new_list)

Above code will give a list containing strings, if you want to convert it into integer type then add this code. This will give your expected output.

for j in range(len(new_list)):
    for k in range(2):
        new_list[j][k] = int(new_list[j][k])
print(new_list)

There are two print statement in above code one will give list of list of string, and after conversion it will give list of list of integers. 输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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