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

  • Python
  • Thread starter Raghav Gupta
  • Start date
  • Tags
    File
In summary: Homework EquationsNAThe Attempt at a Solutionf=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]:
  • #1
Raghav Gupta
1,011
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
  • #2
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.
 
  • #3
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:
  • #4
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:
  • #5

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

1. What is the difference between reading an integer, float, complex number, and boolean value from a file in Python?

When reading from a file in Python, the data is initially read as a string. To convert this string into the desired data type, you can use the built-in functions int(), float(), complex(), and bool(). Integers are whole numbers without decimal points, floats are numbers with decimal points, complex numbers have both real and imaginary parts, and boolean values represent True or False. The main difference between these data types is the way they are stored and the operations that can be performed on them.

2. How can I read multiple data types from a file in Python?

In Python, you can use the split() method to separate the data in a string into a list of strings based on a specified separator. You can then use the appropriate conversion function for each element in the list to convert it to the desired data type. For example, if your file contains a mix of integers and floats separated by spaces, you can use the split() method to create a list and then use int() or float() to convert each element to the desired data type.

3. Can I read data from a file directly into a specific data type in Python?

Yes, you can use the built-in functions int(), float(), complex(), and bool() to read data from a file and convert it to the desired data type. For example, if you know that the data in your file is a float, you can use float(file.readline()) to read and convert the data in one step.

4. How can I handle errors when reading data from a file in Python?

When reading data from a file in Python, it is important to handle errors that may occur. One way to do this is by using a try-except block. Within the try block, you can use the appropriate conversion function to convert the data to the desired data type. If an error occurs, the except block will be executed and you can handle the error accordingly.

5. Can I read data from a file using a specific encoding in Python?

Yes, you can specify the encoding when opening a file in Python using the 'encoding' parameter. For example, if your file is encoded in UTF-8, you can use the following code: file = open("my_file.txt", encoding="utf-8"). This will ensure that the data is read and decoded correctly.

Similar threads

Replies
8
Views
1K
Replies
16
Views
3K
Replies
17
Views
2K
Replies
9
Views
2K
Replies
75
Views
5K
Replies
6
Views
1K
Replies
5
Views
1K
Back
Top