i usually get this error : ValueError: invalid literal for int() with base 10

2024/9/20 7:09:25

I have loaded a csv file and as i try to print it i get this error

Traceback (most recent call last):File "C:\Users\FSTC\Downloads\spaceproject\main.py", line 389, in <module>world_data[x][y]= int(tile)
ValueError: invalid literal for int() with base 10: '-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-

I am suspecting my program but don't know where exactly is the problem.

This is where I loaded and called it:

world_data = []
for row in range(ROWS):r = [-1] * COLSworld_data.append(r)
# load in level data and create world
with open(f"level{level}.csv", newline="") as csvfile:reader = csv.reader(csvfile, delimiter=",")for x, row in enumerate(reader):for y, tile in enumerate(row):world_data[x][y]= int(tile)print(world_data)

variable declaration

level = 1
ROWS = 16
COLS = 150
TILE_SIZE = screen_height // ROWS
TILE_TYPES = 21
[[-1][-1][1]],[-1][1][-1][-1]]
[[-1][-1][1]],[-1][1][-1][-1]]

in the first for loop, i want to get all the items in the rows.. then in the second for loop i want to get each particular item or number in a row which i called a tile. tha's just an excerpt of my main csv file.

Answer

If you have a .csv file with rows like this...

[[-1][-1][1]],[-1][1][-1][-1]]
[[-1][-1][1]],[-1][1][-1][-1]]

You'll read in each row as a list of strings when you call this in your code:

for x, row in enumerate(reader):

So now, each row would look like...

['[[-1][-1][1]]', '[-1][1][-1][-1]]'] # row 1 
['[[-1][-1][1]]', '[-1][1][-1][-1]]'] # row 2

Do you see what the problem is here? The internal items are still strings, but you're trying to treat them as lists when you do this:

for y, tile in enumerate(row):

You would be iterating over the '[[-1][-1][1]]' and '[-1][1][-1][-1]]' strings because the CSV reader doesn't do any sort of type translation from str to Python objects, so when calling int(tile) you're actually doing something like this:

int('[[-1][-1][1]]')

What you need to do instead is to convert those strings in your CSV into the individual elements.

One way to do this would be to remove all brackets from your string and have only the integers inside them, and for that you could re.split() the string on [ and ] and then iterate through just the numbers:

import csv
import re# just making our dummy board of 2 x 7
# for sample tiles.csv
world_data = []
world_data.append([None] * 7)
world_data.append([None] * 7)# load in level data and create world
with open("tiles.csv", newline="") as csvfile:reader = csv.reader(csvfile, delimiter=",")for x, row in enumerate(reader):# I don't know how your 'rows' actually are supposed# to be used since each 'row' in your csv is# a list of lists, but I assume each row is just all the# columns so I'm joining everything togethercols = ''.join(row)# this filters out the None values# from splitting a stringtiles = (t for t in re.split(r"\[|]", cols) if t)for y, tile in enumerate(tiles):world_data[x][y]= int(tile)print(f"world_data: {world_data}")

And this should work and output...

world_data: [[-1, -1, 1, -1, 1, -1, -1], [-1, -1, 1, -1, 1, -1, -1]]

And for reference, my tiles.csv is just a file that looks like this:

> cat tiles.csv
[[-1][-1][1]],[-1][1][-1][-1]]
[[-1][-1][1]],[-1][1][-1][-1]]
https://en.xdnf.cn/q/119395.html

Related Q&A

How to Draw a triangle shape in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 1…

DataFrame from list of string dicts with array() values

So I have a list where each entry looks something like this: "{A: array([1]), B: array([2]), C: array([3])}"I am trying to get a dataframe that looks like thisA B C 0 1 2 3 1 4 …

Need Help Making Buttons to perform for loops when you input a number

I am trying to make a button in Maya using Python that when you type in a number the for loop would loop for that many times. For example, I would put 5 in the box so the for loop would loop 5 times re…

Combining multiple conditional expressions in a list comprehension

I utf-8 encode characters like \u2013 before inserting them into SQLite.When I pull them out with a SELECT, they are back in their unencoded form, so I need to re-encode them if I want to do anything w…

Arduino Live Serial Plotting with a MatplotlibAnimation gets slow

I am making a live plotter to show the analog changes from an Arduino Sensor. The Arduino prints a value to the serial with a Baudrate of 9600. The Python code looks as following: import matplotlib.pyp…

Hide lines on tree view - openerp 7

I want to hide all lines (not only there cointaner) in sequence tree view (the default view). I must hide all lines if code != foo but the attrs atribute dont work on tree views, so how can i filter/hi…

Python Append dataframe generated in nested loops

My program has two for loops. I generate a df in each looping. I want to append this result. For each iteration of inner loop, 1 row and 24 columns data is generated. For each iteration of outer loop, …

bError could not find or load main class caused by java.lang.classnotfoundation error

I am trying to read the executable jar file using python. That jar file doesnt have any java files. It contains only class and JSON files. So what I tried is from subprocess import Popen,PIPEjar_locati…

Invalid value after matching string using regex [duplicate]

This question already has answers here:Incrementing a number at the end of string(2 answers)Closed 3 years ago.I am trying to match strings with an addition of 1 at the end of it and my code gives me t…

How to fetch specific data from same class div using Beautifulsoup

I have a link : https://www.cagematch.net/?id=2&nr=448&gimmick=Adam+Pearce In this link there data in divs with same class name. But I want to fetch specifi div. Like I want to fetch current g…