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
  reading json file DrBrownStats 1 77 Yesterday, 09:00 AM
Last Post: Larz60+
  Python reading variable in another py file wrongly _vertig0 2 126 Nov-21-2020, 07:19 AM
Last Post: _vertig0
  Strange Problem when reading from excel faryad13 3 138 Nov-04-2020, 03:48 PM
Last Post: DeaD_EyE
  reading text file with gtts Nickd12 0 155 Oct-22-2020, 09:37 PM
Last Post: Nickd12
  get two characters, count and print from a .txt file Pleiades 9 399 Oct-05-2020, 09:22 AM
Last Post: perfringo
  Trouble with reading csv file and putting it into a file Milfredo 3 312 Sep-04-2020, 05:30 AM
Last Post: Milfredo
  Reading SQL scripts from excel file and run it using python saravanatn 2 438 Aug-23-2020, 04:49 PM
Last Post: saravanatn
  Ignore first few letters of a line when reading file. ShakeyPakey 16 965 May-30-2020, 02:17 PM
Last Post: BitPythoner
  Reading serial data and saving to a file Mohan 1 521 May-25-2020, 04:18 PM
Last Post: pyzyx3qwerty
  Problem reading data from file player1681 2 402 May-22-2020, 08:57 AM
Last Post: player1681

Forum Jump:

User Panel Messages

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