I have a file that has a bunch of numbers, but there are headings that are keeping me from doing much. The file looks like this:
x:
1 2 3 4
f:
5 6 7 8
h:
9 10 11 12 13
so I have this program which i believe will help me access the numbers but I get an error message about it.
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)
So i tried striping the headers, but I get an error message about it being a string and such.
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)
any advice?
Example
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]
or
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]
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.