簡體   English   中英

如何使用python從文件中僅讀取數字以列為整數

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

我有一個這樣的txt文件:

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

我想將整數0 1 2 3 4 5 6 7 0讀取到列表中。 這是我的代碼:

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

輸出是

0 1 2 3 4 5 6 7 0

但是當我添加"print(linestr[0]+1)" ,它顯示錯誤"TypeError: must be str, not int"這是否意味着我得到的列表仍然不是整數? 如何在此列表中使用數字作為 int? 謝謝所有

它仍然是一個字符串。 通過type(linestr)測試。 您不能向字符串添加整數。

您需要做的是從liststr提取每個值。 這可以使用strip()輕松完成並遍歷此列表以獲取每個值,接下來您需要將其傳遞給int()以將每個值轉換為整數,將其附加到您的帶有整數的列表中,然后您可以使用它正如預期的那樣:

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

print(new_linestr[0]+1)

或作為單襯:

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

您不能在print() strint

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

你可以:

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您的原始導入是一個糟糕的解決方法,請學習使用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