Python Forum

Full Version: Reading integers from a file; the problem may be the newline characters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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? Wall
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())
Output:
['10 23 100 9 2\n', '15 63 9 13 55\n', '8 0 69 20 22 9\n', '10 25 33 42 5 8\n'] 10 23 100 9 2 15 63 9 13 55 8 0 69 20 22 9 10 25 33 42 5 8
You've identified that the delimiter is a space. So you should be thinking that you will need to split() the string on spaces.