![]() |
Convert list to interger - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Convert list to interger (/thread-37159.html) |
Convert list to interger - Clives - May-06-2022 Greetings, The csv returns: [114436] I want to get the values as an integer and not list, any pointers appreciated. Thanks Clive ##### CSV id = open(manhole, encoding='utf-8' ) manhole_id = csv.reader(id) next(id, None) rows = () for row in manhole_id: data_manhole_id = [int(item) for item in row] print(data_manhole_id)I still get: Not I also get an error: TypeErrorTypeError: list indices must be integers or slices, not list RE: Convert list to interger - deanhystad - May-06-2022 I assume your file looks like this: 114436 114474 114514 This is not csv format. You do not need a CSV reader. with open("data.csv", "r") as file: for line in file: print(int(line))What you wrote is for data that is actually in csv format 114436,114474,114514 import csv with open('data.csv', "r") as file: reader = csv.reader(file) for row in reader: data = [int(item) for item in row] print(data)
RE: Convert list to interger - Clives - May-06-2022 Hi Dean, Thanks for the advice. I changed the code: line = () with open(data, encoding='utf-8') as manhole_id: #csv_reader = reader(manhole_id) for line in manhole_id: next(manhole_id, None)The next(manhole_id, None) is not working?? It is returning an extra line?? Thanks Clive RE: Convert list to interger - deanhystad - May-06-2022 If the file looks like this: Whatever 114436 114474 114514 You can skip the first line in the file. with open("data.csv", "r") as file: next(file) for line in file: print(int(line)) When using a contact manager (with), the file only remains open for code that is in the context block (indented 1 level deeper than the with). In your latest example the manhole_id file is closed before the for loop executes.
RE: Convert list to interger - Clives - May-09-2022 Apologies typo... It returns: 114806 114810 114831 114841 114843 NOT: 114806 114810 114831 114841 114843 RE: Convert list to interger - deanhystad - May-09-2022 You are doing something wrong. My guess is you are printing the str which has a trailing linefeed. I thought you wanted to read the file and convert to int. |