Reading integers from a file; the problem may be the newline characters - 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: Reading integers from a file; the problem may be the newline characters (/thread-28313.html) |
Reading integers from a file; the problem may be the newline characters - JRWoodwardMSW - Jul-14-2020 I want to read integers from a file. The delimiter is " " (a space). I am getting the list of strings read into the program, but the error message is: ValueError: invalid literal for int() with base 10: Here is my code: import os os.path.join("Users", "admin", "PycharmProjects", "althhoff", "open_nums_test.txt") f = open('open_nums_test.txt', "r") test_list = f.readlines() print (test_list) test_list = list(map(int, test_list)) print("Integer list is : " + str(test_list)) When I print(test_list), I notice than both lists end in newlines - '\n'. Is the newline character causing the ValueError? Is map choking as it tries to int a "\n"? If so, what can I do about it? RE: Reading integers from a file; the problem may be the newline characters - menator01 - Jul-14-2020 Someone correct me if I'm wrong but, you're testing for an integer in a string. #! /usr/bin/env python3 with open('num.txt', 'r') as lines: lines = lines.readlines() print(list(map(str, lines))) for line in lines: print(line.strip())
RE: Reading integers from a file; the problem may be the newline characters - bowlofred - Jul-14-2020 You've identified that the delimiter is a space. So you should be thinking that you will need to split() the string on spaces.
|