Python Forum
Reading integers from a file; the problem may be the newline characters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading integers from a file; the problem may be the newline characters
#1
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
Reply
#2
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
Reply
#3
You've identified that the delimiter is a space. So you should be thinking that you will need to split() the string on spaces.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Helps with reading csv file - 3 methods hhchenfx 4 126 Yesterday, 04:15 AM
Last Post: buran
  Subprocess.Popen() not working when reading file path from csv file herwin 13 389 May-07-2021, 03:26 PM
Last Post: herwin
  How to make print without newline but wait in between each print? Adrian_L 6 351 Apr-01-2021, 09:59 PM
Last Post: Adrian_L
  find the header location in a .bin file without reading the whole file at a time SANJIB 0 245 Mar-05-2021, 04:08 PM
Last Post: SANJIB
  Reading a csv file Led_Zeppelin 2 427 Feb-26-2021, 05:48 AM
Last Post: buran
  reading a csv file Led_Zeppelin 3 577 Feb-19-2021, 02:16 PM
Last Post: Led_Zeppelin
  Split Characters As Lines in File quest_ 3 451 Dec-28-2020, 09:31 AM
Last Post: quest_
  Code not reading http link from .txt file (Beginner level) plarrip 3 406 Dec-17-2020, 11:33 PM
Last Post: bowlofred
  Reading from a file. krhoades 3 418 Dec-03-2020, 09:52 PM
Last Post: krhoades
  reading json file DrBrownStats 1 327 Nov-25-2020, 09:00 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020