Python:Reading (int,float,comp,bool) from file

  • Context: Python 
  • Thread starter Thread starter Raghav Gupta
  • Start date Start date
  • Tags Tags
    File
Click For Summary
SUMMARY

The discussion focuses on reading comma-separated numeric values (int, float, complex, bool) from a file named "qwerty.txt" and sorting them without using built-in sorting functions. The initial approach attempted to typecast all values to integers, which caused errors when encountering floats. The solution involves determining the type of each value using Python's type conversion functions and appending them to a list accordingly. The final output is to be written to "output.txt" in a comma-separated format without quotes.

PREREQUISITES
  • Understanding of Python file handling
  • Familiarity with Python data types: int, float, complex, bool
  • Knowledge of exception handling in Python
  • Basic sorting algorithms, specifically bubble sort
NEXT STEPS
  • Implement type checking for values using Python's exception handling
  • Research Python's built-in functions for type conversion: int(), float(), complex(), bool()
  • Learn about custom sorting algorithms and their implementation in Python
  • Explore Python's list comprehensions for more efficient list manipulation
USEFUL FOR

Students, Python developers, and anyone interested in file I/O operations and data type handling in Python.

Raghav Gupta
Messages
1,010
Reaction score
76

Homework Statement


Read a comma separated numeric (int, float, comp, bool) values from a file and store each
comma separated value in a list[/B]. Sort the list (without using in-built sort/sorted function)
and write it to output file in comma separated format.

In my attempt I am not able to do the bold part in the question. That is if float value is there in file then it cannot be typecasted to int. How do I typecast with conditions?

Homework Equations


NA

The Attempt at a Solution


Python:
f=open("qwerty.txt","r")
y=[]
for line in f:
    x=line.split(',')
    for val in x:
       y.append(int(val))  # Here if float is stored in file then it cannot be typecasted to int.
for i in range(len(y)-1):    # Doing bubble sort
    for j in range(len(y)-i-1):
        if y[j]>y[j+1]:
            y[j],y[j+1]=y[j+1],y[j]
f.close()
f=open("output.txt","w")
f.write(str(y)[1:-1])
f.close()
 
Technology news on Phys.org
Raghav Gupta said:

Homework Statement


Read a comma separated numeric (int, float, comp, bool) values from a file and store each
comma separated value in a list[/B]. Sort the list (without using in-built sort/sorted function)
and write it to output file in comma separated format.

In my attempt I am not able to do the bold part in the question. That is if float value is there in file then it cannot be typecasted to int. How do I typecast with conditions?

Homework Equations


NA

The Attempt at a Solution


Python:
f=open("qwerty.txt","r")
y=[]
for line in f:
    x=line.split(',')
    for val in x:
       y.append(int(val))  # Here if float is stored in file then it cannot be typecasted to int.
for i in range(len(y)-1):    # Doing bubble sort
    for j in range(len(y)-i-1):
        if y[j]>y[j+1]:
            y[j],y[j+1]=y[j+1],y[j]
f.close()
f=open("output.txt","w")
f.write(str(y)[1:-1])
f.close()
Is the idea just to read values from the file and store them in a list? If so, why do you need to cast a floating point value to an integer value? The problem description you have doesn't mention doing this.
 
Mark44 said:
Is the idea just to read values from the file and store them in a list? If so, why do you need to cast a floating point value to an integer value? The problem description you have doesn't mention doing this.
But we have to sort, so we have to convert it into numeric type.
EDIT: Ok, so we can compare them as strings only. It would compare lexicographically based on ASCII values but if we store them in file again, it is stored something like this-
'1' , '2+j', '3.5', '4', 'FALSE', 'TRUE'
This is storing the list contents in string format. I want output like this-
1, 2+j, 3.5, 4, FALSE, TRUE
without quotes
For that I have to typecast finally?
 
Last edited:
Raghav Gupta said:
Python:
f=open("qwerty.txt","r")
y=[]
for line in f:
    x=line.split(',')
    for val in x:
       y.append(int(val))  # Here if float is stored in file then it cannot be typecasted to int.
The problem is that the text file doesn't contain floats or integers or complex numbers -- it contains text. Your variable x is a list that contains strings. For example, if the first line of the input file is 3.5, 2, true, the list x will look like ['3.5', '2', 'true'].
The reason that int(val) throws an exception (ValueError) is that int() can't be used on strings. For the same reason, float(), bool(), and complex() will fail when applied to strings.

What you need to do for each value you get from the file is figure out if it's a complex or float or integer or Boolean. One way to do this is to have four other variables, with each initialized to a value of one of these four types (complex, float, integer, Boolean).
Python:
v_cplex = 1+2j
v_float = 1.5
v_int = 1
v_bool = True
There's nothing special about the initializations I did above. I just want four variables with each of a specific type.

For a given val, try assigning it to each of the above variables. If you assign val to f_float, for example, and get an error (ValueError), you know that val isn't a float value. After you determine that val is, say, a float, append v_float to your list y.

Edit: One more thing. If you write the various values to a list as numbers, you won't be able to sort them, as complex numbers aren't comparable to real variables (such as int, float, bool).
 
Last edited:

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 16 ·
Replies
16
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 75 ·
3
Replies
75
Views
6K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
1
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K