我有一个包含大量数字的文件,但有些标题让我无法做太多事情。该文件如下所示:
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)
任何建议?
答案 0 :(得分:-1)
实施例
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]