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
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


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
  Last record in file doesn't write to newline gonksoup 3 364 Jan-22-2024, 12:56 PM
Last Post: deanhystad
Sad problems with reading csv file. MassiJames 3 559 Nov-16-2023, 03:41 PM
Last Post: snippsat
  Facing issue in python regex newline match Shr 6 1,142 Oct-25-2023, 09:42 AM
Last Post: Shr
  Reading a file name fron a folder on my desktop Fiona 4 851 Aug-23-2023, 11:11 AM
Last Post: Axel_Erfurt
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,046 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
Question How to append integers from file to list? Milan 8 1,358 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  Reading a file JonWayn 3 1,057 Dec-30-2022, 10:18 AM
Last Post: ibreeden
  Reading Specific Rows In a CSV File finndude 3 940 Dec-13-2022, 03:19 PM
Last Post: finndude
  Excel file reading problem max70990 1 865 Dec-11-2022, 07:00 PM
Last Post: deanhystad
  Replace columns indexes reading a XSLX file Larry1888 2 951 Nov-18-2022, 10:16 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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