![](/img/trans.png)
[英]Python - how can i read numbers in a file as integers but with headings?
[英]How do I take numbers from a file and read them as integers if they have headings in python?
我有一個包含一堆數字的文件,但有些標題使我無法做很多事情。 該文件如下所示:
x:
1 2 3 4
f:
5 6 7 8
h:
9 10 11 12 13
所以我有這個程序,我相信它可以幫助我訪問這些號碼,但我收到一條關於它的錯誤消息。
filename = input('file: ')
f = open(filename, 'r')
output=[]
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
if i == h:
break
x.append(map(int,line.split()[:w]))
output.append(x)
所以我嘗試對標題進行條帶化,但是我收到一條關於它是一個字符串等的錯誤消息。
filename = input('file: ')
f = open(filename, 'r')
output=[]
func = f.readline()
lines = func.strip('x').strip('f').strip('h').split()
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
if i == h:
break
x.append(map(int,line.split()[:w]))
output.append(x)
有什么建議嗎?
例子
filename = input('filename: ')
with open(filename, 'r') as f:
for line in f: # line one-by-one
line = line.strip() # strip to check empty lines
if line: # skip empty lines
elements = line.split()
print(elements[2]) # [column]
或者
filename = input('filename: ')
# get not empty lines
lines = []
with open(filename, 'r') as f:
for line in f: #
line = line.strip() # strip to check empty lines
if line: # skip empty lines
elements = line.split()
lines.append(elements)
# work with lines one-by-one
for line in lines: #
print(line[2]) # [column]
# direct access to any element
print(lines[1][2]) # [row][column]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.