I am trying to encode a set of coordinates taken from a csv file using google's polyline.encode funcion. This function takes coordinates in the following format
polyline.encode([(38.5, -120.2), (40.7, -120.9), (43.2, -126.4)], 5)
I read every line of the csv and format and pass it to a variable and then adding brackets so that the polyline.encode can run it. However my code breaks there. Do i need to convert it to a string?
This is my for loop function which formats the coords correctly
filename = 'coords.csv'
file = open(filename, encoding="utf8")
result = ""
for line in file:
currentline = line.split(",")
result += '('+currentline[1]+', '+ currentline[2]+')'+','
coords = f'[{result}]'
print(coords)
which then prints the coordinates
Then i try to call
polyline.encode(coords)
and my script breaks
EDIT: the polyline requires me to give the coordinate sin tuple format
:param coordinates: List of coordinate tuples, e.g. [(0, 0), (1, 0)].
Any help or advice is appreciated.
You need to use the a list composed of the Tuple data type and right now you're just using a string formatted to look like an list of Tuple elements.
Try this:
filename = 'coords.csv'
file = open(filename, encoding="utf8")
coords= []
for line in file:
currentline = line.split(",")
coords.append(( float(currentline[1]), float(currentline[2]) ))
print(coords)
polyline.encode(coords)
Related
How can I change the format of a string so that ImageGrab accepts it?
My task is to get the coordinates for the container from the file and paste their values into the box.
There is only one line in the file and it has the format: 335,50,467,70.
If I substitute these values directly, and not through a variable, the script works perfectly. But he refuses to take values from the file.
What do i do?
from PIL import ImageGrab
with open(r"C:\Users\admin\Desktop\area.txt", "r") as file:
lines = file.readline()
print(lines)
box = (lines)
#box = (335,50,467,70) # If so, then everything works perfectly
print(box)
img = ImageGrab.grab(box)
#img.show()
To expand on my comment a little, you have a string: lines = "335,50,467,70"
You can split the string by separating across the commas to give a list of strings, like so:
box = lines.split(',')
box
>>> ["335", "50", "467", "70"]
Then, you can iterate over the list and cast each item to an int like so:
box = tuple(int(item) for item in lines.split(','))
box
>>> (335, 50, 467, 70)
I know how to print one value of variable but I have a problem with more variables into one line.
file = open("values","w+")
file.write(str(q+q_krok+omega+omega_krok+e+e_krok))
The desired files values:
1-8-9-9-6-6
I would like to print values of 6 variables into file and between them put some value, for instance -. Thank you
Put the values into a string, then simply write that string to file.
values = <whatever your values are, as a string>
with open(“values.txt”, “w”) as f:
f.write(values)
If you have a list of values, you could create the string by using a join statement.
val_list = [1, 2, 3, 4, 5]
values = '-'.join(val_list)
If you have a specific set of values stored in different vars, you could use an f-string.
values = f'{val1}-{val2}-{val3}-{val4}'
Try doing it this way:
li = [q,q_krok,omega,omega_krok,e,e_krok]
values = '-'.join(li)
with open("values_file", "w") as f:
f.write(values)
You can even do it this way:
file = open("values_file","w+")
file.write(values)
You can have the values into a list, like:
items = [1,8,9,9,6,6]
with open('test.txt, 'r') as f:
for elem in items[:-1]: -- for each element instead of last
print(elem, end="-") -- print the value and the separator
if (len(items) > 1):
print(items[-1]) -- print last item without separator
A very well-made tutorial about reading/writing to files in python can be watched here:
https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=1264s
I'm trying to read a csv file, and create a 2 dimensional list from the values stored inside.
However I'm running into trouble when I try to check whether or not the values stored can be converted into floats.
Here is the function I have written, which reads the file and creates a list.
def readfile(amount, name):
tempfile = open(name).readlines()[1:] #First value in line is never a float, hence the [1:]
rain_list = []
count = 0.0
for line in tempfile:
line = line.rstrip()
part = line.split(",")
try:
part = float(part)
except ValueError:
print("ERROR: invalid float in line: {}".format(line))
rain_list.append(part[amount])
count += 1
if count == 0:
print("ERROR in reading the file.")
tempfile.close()
return rain_list
It might be a little messy, since it's essentially a patchwork of different possible solutions I have tried.
The values it gets are the name of the file (name) and the amount of values it reads from the file (amount).
Has anyone got an idea why this does not work as I expect it to work?
part is a list of strings. To check & convert for all floats, you'd have to do:
part = [float(x) for x in part]
(wrapped in your exception block)
BTW you should use the csv module to read comma-separated files. It's built-in. Also using enumerate would allow to be able to print the line where the error occurs, not only the data:
reader = csv.reader(tempfile) # better: pass directly the file handle
# and use next(reader) to discard the title line
for lineno,line in enumerate(reader,2): # lineno starts at 2 because of title line
try:
line = [float(x) for x in line]
except ValueError:
print("ERROR: invalid float in line {}: {}".format(lineno,line))
I can't seem to pull each individual line from a .txt file into a tuple. The 'city-data.txt' file is just a list of the 50 states, capitols, and their lat/longs. I need to create a tuple of all the states.
This is my code so far -
def read_cities(file_name):
file_name = open('city-data.txt' , 'r')
for line in file_name:
road_map = ((line.split('\t')))
return road_map
file_name.close()
print(read_cities('city-data.txt'))
When it's run, it only prints the very first line from the .txt file, as such:
['Alabama', 'Montgomery', '32.361538', '-86.279118\n']
The reason it prints only the very first line is because of this
for line in file_name:
road_map = ((line.split('\t')))
return road_map
You are returning immediately after you consume the first line. This is why it only prints the very first line.
Instead, you need to store these in a list, and return that list in the end.
def read_cities(file_name):
file_name = open('city-data.txt' , 'r')
road_maps = []
for line in file_name:
road_map = ((line.split('\t')))
road_maps.append(road_map)
file_name.close()
# road_maps is a list, since you wanted a tuple we convert it to that
return tuple(road_maps)
print(read_cities('city-data.txt'))
I need to create a tuple of all the states.
Does this mean you only want the first column from each line ? If so, modify it to
def read_cities(file_name):
# notice I've changed this to use file_name instead of
# the hard-coded filename string
file_name = open(file_name , 'r')
# if you need uniqueness, use states=set() and use .add instead
# of .append
states = []
for line in file_name:
line_split = line.split('\t')
# line_split is a list and the 0th index is the state column
state = line_split[0]
# use states.add if you used a set instead of a list
states.append(state)
file_name.close()
return tuple(states)
print(read_cities('city-data.txt'))
I have this file that contains something like this:
OOOOOOXOOOO
OOOOOXOOOOO
OOOOXOOOOOO
XXOOXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
And I need to read it into a 2D list so it looks like this:
[[O,O,O,O,O,O,X,O,O,O,O],[O,O,O,O,O,X,O,O,O,O,O],[O,O,O,O,X,O,O,O,O,O,O],[X,X,O,O,X,O,O,O,O,O,O],[X,X,X,X,O,O,O,O,O,O,O,O],[O,O,O,O,O,O,O,O,O,O,O]
I have this code:
ins = open(filename, "r" )
data = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
numbers = [(n) for n in number_strings]
data.append(numbers) # Add the "row" to your list.
return data
But it doesn't seem to be working because the O's and X's do not have spaces between them. Any ideas?
Just use data.append(list(line.rstrip())) list accepts a string as argument and just splits them on every character.