I have a list of numbers that read left to right in a text file and I'm trying to get Python to read them as a list of numbers so that I can eventually graph them. I've been trying various string, pickle, and byte to string codes but inevitably end up with errors. example of the numbers
20494 20461 20461 20459 20464 20470 20478 20483 20487 20486 20486
20486 20484 20481 20479 20475 20473 20473 20473 20470 20470 20471
20475 20478 20481 20481 20480 20479 20475 20473 20472 20471 20470
20468 20468 20467 20467 20466 20470 20474 20480 20483 20481 20480
20481 20485 20487 20487 20485 20482 20481 20479 20477 20474 20474
20475 20477 20479 20476 20469 20467 20473 20478 20487 20487 20476
20477 20488 20490 20484 20483 20480 20486 20494 20497 20495 20492
20485 20498 20530 20530 20502 20502 20522 20536 20525 20520 20549
20560 20503 20499 20584 20607 20518 20478 20525 20542 20490 20472
the code I have tried
with open('r1a disp press') as f:
polyShape = []
for line in f:
line = line.split()
if line:
line = [int(i) for i in line]
polyShape.append(line)
import pickle
import io
press = io.StringIO()
picklestring = pickle.dump(polyShape, press)
print (pickleString)
I can print the polyshape but I get the error "string argument expected, got 'bytes'" after the picklestring
split and int is your friend:
with open(filename) as text:
numbers = [int(n) for n in text.read().split()]
If you want you can copy the numbers in the python code as well as given below:
a="""20494 20461 20461 20459 20464 20470 20478 20483 20487 20486 20486
20486 20484 20481 20479 20475 20473 20473 20473 20470 20470 20471
20475 20478 20481 20481 20480 20479 20475 20473 20472 20471 20470
20468 20468 20467 20467 20466 20470 20474 20480 20483 20481 20480
20481 20485 20487 20487 20485 20482 20481 20479 20477 20474 20474
20475 20477 20479 20476 20469 20467 20473 20478 20487 20487 20476
20477 20488 20490 20484 20483 20480 20486 20494 20497 20495 20492
20485 20498 20530 20530 20502 20502 20522 20536 20525 20520 20549
20560 20503 20499 20584 20607 20518 20478 20525 20542 20490 20472"""
results=a.split()
results = [int(i) for i in results]
print results
Fixing up the code you posted, first lets fix your indentation. Shift everything below your with
statement up to an including your polyShape.append()
line over by one indentation.
Next, lets get rid of your list comprehension, and replace it with a for-loop over the elements of line
. In the for-loop, convert the element to an int and append it to your polyShape
list like so:
with open('r1a disp press') as f:
polyShape = []
for line in f:
line = line.split()
if line:
#line = [int(i) for i in line]
#polyShape.append(line)
for num in line:
polyShape.append(int(num))
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.