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
Download my project scripts


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
  using last 2 characters of a file name to identify it CAD79 5 1,745 Jul-12-2024, 02:09 PM
Last Post: deanhystad
  Reading an ASCII text file and parsing data... oradba4u 2 1,403 Jun-08-2024, 12:41 AM
Last Post: oradba4u
  Last record in file doesn't write to newline gonksoup 3 1,555 Jan-22-2024, 12:56 PM
Last Post: deanhystad
Sad problems with reading csv file. MassiJames 3 2,523 Nov-16-2023, 03:41 PM
Last Post: snippsat
  Facing issue in python regex newline match Shr 6 6,010 Oct-25-2023, 09:42 AM
Last Post: Shr
  Reading a file name fron a folder on my desktop Fiona 4 2,061 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 2,089 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
Question How to append integers from file to list? Milan 8 2,871 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  Reading a file JonWayn 3 1,934 Dec-30-2022, 10:18 AM
Last Post: ibreeden
  Reading Specific Rows In a CSV File finndude 3 1,814 Dec-13-2022, 03:19 PM
Last Post: finndude

Forum Jump:

User Panel Messages

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