Error: invalid literal for int() with base 10: ' ' - python

How to read the file with the numbers and save it in the list?
I tried this way but i got the error: ValueError: invalid literal for int() with base 10: ''
I would be grateful for your help and apologize for the grammar mistake.
The code:
file = open("edges.txt", "r")
list1 = []
for x in file.readlines():
list1.append([int(k) for k in x.rstrip("\n").split(" ")])
The content of my txt. file is:
1 2
3 5
2 4
4 6
It should look like:
[1, 2]
[3, 5]
[2, 4]
[4, 6]

Let's break it down, this:
list1.append([int(k) for k in x.rstrip("\n").split(" ")])
Is the equivalent of this:
list1 = []
for k in x.rstrip("\n").split(" "):
list1.append(int(k))
As you can see, k is clearly a part of a string, and the error means that it isn't a number. Try this:
file = open("edges.txt", "r")
list1 = []
for x in file.readlines():
list1.append([int(k) for k in x.rstrip("\n").split(" ") if k.isdigit()])
But in better practice:
with open("edges.txt", "r") as file:
list1 = []
for x in file.readlines():
list1.append([int(k) for k in x.rstrip("\n").split(" ") if k.isdigit()])

Use isalnum() since you are trying to convert to an integrer

You can use isdigit() of a string to validate that you are trying to convert number to int and another strip() method will help in this case since it seems that one line containing a number with space before or after.
file = open("edges.txt", "r")
list1 = []
for x in file.readlines():
list1.append([int(k) for k in x.rstrip("\n").strip().split(" ") if k.isdigit()])

Related

How do I fix this ValueError?

I am trying to get an average from a text file that uses a def function. I am trying to convert the list from the text file to int(). Instead of converting it gives me the error: " ValueError: invalid literal for int() with base 10: '5, 5, 6, 7' ". The "5, 5, 6, 7" is one that I made from the proper .txt file. Here is the code:
def getNumberList(filename):
with open(filename,'r') as f:
lyst = f.read().split('\n')
numberList = [int(num) for num in lyst]
return numberList
def getAverage(filename, func):
numbers = func(filename)
return sum(numbers)/len(numbers)
def main():
filename = input("Input the file name: ")
average = getAverage(filename, getNumberList)
print(average)
if __name__ == "__main__":
main()
You are splitting by line but you are not splitting by commas, so you are trying to convert 5,5,6,7 to an integer, which is impossible. You need to also split by commas after you split by line, and then combine them into one list, if you want to average all the numbers in the file. The following should work:
def getNumberList(filename):
with open(filename,'r') as f:
lines = f.readlines()
numberList = [int(num) for num in line.split(',') for line in lines]
return numberList
Looks like you might need to split each element with lyst using "," because right now it is trying to convert each line which has "1,2,3" as input.
So, change this and try.
def getNumberList(filename):
with open(filename,'r') as f:
lyst = []
temp = f.read().strip().split('\n')
for i in temp:
lyst += i.strip().split(',')
numberList = [int(num) for num in lyst]
return numberList

Read only the numbers from a txt file python

I have a text file that contains these some words and a number written with a point in it. For example
hello!
54.123
Now I only want the number 54.123 to be extracted an converted so that the outcome is 54123
The code I tried is
import re
exp = re.compile(r'^[\+]?[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
if re.match(exp, line.strip()):
my_list.append(int(line.strip()))
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
But this returns the error: ValueError: invalid literal for int() with base 10: '54.123'
Does anyone know a solution for this?
You can try to convert the current line to a float. In case the line does not contain a legit float number it returns a ValueError exception that you can catch and just pass. If no exception is thrown just split the line at the dot, join the 2 parts, convert to int and add to the array.
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
try:
tmp = float(line)
num = int(''.join(line.split(".")))
my_list.append(num)
except ValueError:
pass
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
You can check if a given line is a string representing a number using the isdigit() function.
From what I can tell you need to just check if there is a number as isdigit() works on integers only (floats contain "." which isn't a number and it returns False).
For example:
def numCheck(string):
# Checks if the input string contains numbers
return any(i.isdigit() for i in string)
string = '54.123'
print(numCheck(string)) # True
string = 'hello'
print(numCheck(string)) # False
Note: if your data contains things like 123ab56 then this won't be good for you.
To convert 54.123 to 54123 you could use the replace(old, new) function.
For example:
string = 54.123
new_string = string.replace('.', '') # replace . with nothing
print(new_string) # 54123
This may help I am now getting numbers from the file I guess you were trying to use split in place of strip
import re
exp = re.compile(r'[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
for numbers in line.split():
if re.match(exp, numbers):
my_list.append(numbers)
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)

How to input a list in Python?

Usually, we input() a list in Python 3.X like this:
x = list(map(int, input()))
print (x)
But here let's say we give an input of 1234 then it prints:`
[1, 2, 3, 4]
Is there a way that I can print it like:
[12, 34]
Thanks in Advance!
Let's say you want the numbers to be entered separated by spaces. First get the entire line as input:
line = input()
Now parse the input. In this case, split on spaces:
words = line.split(' ')
Finally, convert each "word" to an int:
numbers = [int(i) for i in words]
Of course you can use map() instead of a list comprehension.
Note that this requires input such as
12 34
You can do this all in one line, but it is better to use variables to store each intermediate step. When you get it wrong, you can debug much more easily this way.
In my opinion, I would not complicate things :
I would declare an empty list :
l = []
Then I would simply append the input :
for i in range(0, n):
print("l[", i, "] : ")
p = int(input())
l.append(p)
You can notice here the "n",it's the size for the list,in your case it would be:
for i in range(0, 1):
print("l[", i, "] : ")
p = int(input())
l.append(p)
We always start from 0,so range(0,1) would count 0, then 1 and so on with other cases.
Hope this would help.

Reading simple data files manipulating strings.

If I'm given:
point_loads, 3, 500
point_loads, 6, 900
point_loads, 12, 300
This code:
for line in open("Input.txt"):
li=line.strip()
if li.startswith("point_load"):
l = li.split(',')
for num in l[1:]:
num = float(num.strip())
point_loads.append(num)
prints:
point_loads = [3, 500, 6, 900, 12, 300]
I am trying to modify it so that if I'm given:
length = 32
point_loads, 3, 500
point_loads, 6, 900
point_loads, end, 300
It will set 'end' equal to 32 (or the variable length) so that the output is:
point_loads = [3, 500, 6, 900, 32, 300]
I tried a few different things, this was my latest...
for line in open("Input.txt"):
li=line.strip()
if li.startswith("point_load"):
l = li.split(',')
for num in l[1:]:
if num == 'end':
num = 10
num = float(num.strip())
point_loads.append(num)
but it gave me the error: (plus it wouldn't have really have done what I wanted, but it was a start)
num = float(num.strip())
ValueError: could not convert string to float: 'end'
When debugging, I can see that I need to strip the string so that it doesnt preform an operation on ' end'.
I've tried messing around with different bits of code for a few hours now, but have made no progress.
Any tips for this part?
Thank you!
I'm not sure. But it might what you want?
for line in open("Input.txt"):
li = line.strip()
if li.startswith("point_load"):
l = li.split(', ')
for num in l[1:]:
if num == 'end':
num = '10'
num = float(num.strip())
point_loads.append(num)
l = li.split(',') turns to l = li.split(', '), use both , and to split string to list
num = 10 turns to num = '10' make all elements are string to call strip()
If I understand your problem, you are unable to exchange the string 'end' with a variable of your choosing. Based on what you've said, it's because you are not matching strings correctly first. When you split the line by comma, you are still getting whitespace for each item.
'point_loads, end, 300'.split() ends up as `['point_loads', ' end', ' 300']
In order to fix this I would first filter your lines to strip all whitespace from each item after the split. Then when you test if num == 'end' you will get True. Your current code is testing if 'end' == ' end' which is False.
point_loads = []
with open(path, 'r') as f:
for line in f:
li = line.strip()
if li.startswith("point_load"):
l = li.split(',')
l = [x.strip() for x in l] # strip whitespace from each item
for num in l[1:]:
if num == 'end':
num = 10.
else:
num = float(num.strip())
point_loads.append(num)
I noticed the second part of your problem has to do with the nature of Python and duck typing. You are trying to call a string method strip() on ints and strings. In my above code if it matches your string it assigns an int otherwise it will convert the string to an int thus avoiding the issue of trying to call strip on an int.
EDIT I fixed the code - I had made a typo and used split() instead of strip() in the list comprehension. I tested this in python3.6 but it should also work in python2.7. I added a proper context manager for opening the file too which you should always do.

Python Subtract integers in List to return a value

I would like to take a large file like this in Python 2.7:
123 456 GTHGGGTH
223 567 FGRTHSYS
12933 4656832 GJWSOOOSKKSSJ
.....
and I want to read in the file line by line, disregard the third element, and subtract the second element in each line by the first element. Thus line 1 above would return 333.
I have tried this so far:
def deleteLast(list):
NewL = list.pop()
return NewL
f = open(file_name, 'r')
line = f.readline()
while line:
L = line.split()
L2 = deleteLast(L)
L3 = [int(number) for number in L2]
Length = L3[1]-L3[0]
print Length
f.close()
But, when I try this the compiler says:
ValueError: invalid literal for int() with base 10: 'T'
All help is appreciated.
That is because list.pop() is returning the "popped off" item, it doesn't return the list again.
Instead of this deleteLast function you have written, it would be better just to use a slice like this:
L2 = line.split()[0:2]
You are going to run into another problem later because your while loop isn't advancing at all. Consider using a for loop instead.
You can try something like this :
In [8]: with open("abc") as f: #always use with statement when handling files
...: for line in f:
...: x,y=map(int,line.split()[:2])
...: print y-x
...:
333
344
4643899
try the following:
with open(file_name, 'r') as f:
for line in f.readlines():
rowData = line.split()
left, right = map(int, rowData[:2])
length = right - left
print length
Or:
from operator import sub
with open(file_name, 'r') as f:
for line in f.readlines():
print sub(*map(int, line.split()[:2])[::-1])
f = open(file_name, 'r')
for line in f.readlines():
x, y = line.split(' ')[:2]
print int(y) - int(x)

Categories

Resources