简体   繁体   English

如何使用python从文件中仅读取数字以列为整数

[英]How to read numbers only to list as integer, from a file using python

I have a txt file like this:我有一个这样的txt文件:

input 0 1 2 3 4 5 6 7 0
output 127 191 223 239 247 251 253 254 0

I want to read integers 0 1 2 3 4 5 6 7 0 to a list.我想将整数0 1 2 3 4 5 6 7 0读取到列表中。 Here is my code:这是我的代码:

f=open('data.txt','r')
for line in f:
        if 'input' in line:
                linestr=line.strip('input')
                #linestr=list(map(int,linestr)
                print(linestr)

The output is输出是

0 1 2 3 4 5 6 7 0

But when i add "print(linestr[0]+1)" , it shows error "TypeError: must be str, not int" Is that means the list I got is still not integer?但是当我添加"print(linestr[0]+1)" ,它显示错误"TypeError: must be str, not int"这是否意味着我得到的列表仍然不是整数? How can I use the number as int in this list?如何在此列表中使用数字作为 int? Thx all谢谢所有

It is still a string.它仍然是一个字符串。 Test this by type(linestr) .通过type(linestr)测试。 You cannot add an integer to a string.您不能向字符串添加整数。

What you need to do is extract each value from liststr .您需要做的是从liststr提取每个值。 This can be done easily using strip() and running through this list to get each value, next you need to pass it to int() to turn each value into an integer, append it to your list with integers, then you can use it as expected:这可以使用strip()轻松完成并遍历此列表以获取每个值,接下来您需要将其传递给int()以将每个值转换为整数,将其附加到您的带有整数的列表中,然后您可以使用它正如预期的那样:

new_liststr = []
for i in liststr.split():
    new_liststr.append(int(i))

print(new_linestr[0]+1)

Or as a single liner:或作为单衬:

new_liststr = [int(i) for i in liststr.split()] 
print(new_linestr[0]+1)

You can not att a str and an int inside a print()您不能在print() strint

print(linestr[0]+1)
                 ^
                 |
             not a str

You can:你可以:

print(int(linestr[0])+1)
from pathlib import Path
doc="""input 0 1 2 3 4 5 6 7 0
output 127 191 223 239 247 251 253 254 0"""
Path('temp.txt').write_text(doc)

with open('temp.txt','r') as f:
    for line in f:
        if 'input' in line:
             linestr=line.strip('input')

# here is what you have accomplished:
assert linestr == ' 0 1 2 3 4 5 6 7 0\n'
assert linestr == ' '
#you are tying to do ' '+1

linelist = map(int, linestr.strip().split(' '))
assert linestr[0]+1 == 1

PS your original import is a terrible workaround, please learn to use https://docs.python.org/3/library/csv.html PS您的原始导入是一个糟糕的解决方法,请学习使用https://docs.python.org/3/library/csv.html

output = []
with open('data.txt','r') as f:
    for line in f:
        l = line.split()
        if l[0] == 'input':
            output.extend(map(int, l[1:]))

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

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