I'm trying to change the unit of a value in a text file. First part of the task was to turn the string list to a float, but now (without using index()) I want to change the unit of the elemets which are kbps to mbps, so the 1200 value to 1.2.
This is the code that turns the values of the list to float:
bw = [] #another comment: create an empty list
with open("task4.txt") as file_name:
for line in file_name:
a = line.split() #The split() method splits a string into a list - whitspace as a default
bw.append(a[0]) #only appending the first value
floats = [float(line) for line in bw] #Turnes the string into a float
print(bw)
The text file looks like this:
7 Mbps
1200 Kbps
15 Mbps
32 Mbps
I need the list to become 7, 1.2, 15, 32 without changing the textfile, nor use index. I want a programs that finds all kbps values and turns them into mbps
CodePudding user response:
You have to check the first letter of the units to determine whether to divide by 1000 to convert Kpbs to Mbps.
bw = [] #another comment: create an empty list
with open("task4.txt") as file_name:
for line in file_name:
speed, unit = line.split()
speed = float(speed)
if unit.startswith('K'):
speed /= 1000
bw.append(speed)
print(bw)
CodePudding user response:
If you want both the Mbps and Kbps in the list you could try my code below:
with open('task4.txt', 'r') as file:
sizes = []
for line in file:
size, unit = line.strip().split()
if unit == 'Mbps':
sizes.append(float(size))
else:
sizes.append(float(size)/1000)
print(sizes)
CodePudding user response:
To start, you can open and parse the file into a list
by line:
speeds = []
with open("task4.txt", "r", encoding="utf-8") as file:
speeds = file.read().splitlines()
After reading the file, the task becomes a one-liner.
speeds = [str(int(x.split()[0]) / 1000) " " x.split()[1] if "kbps" in x.lower() else x for x in speeds]
For readability's sake, I have included a more verbose solution with comments here, although it does the exact same thing as the above:
# Create a temporary array to hold the converted speeds
new_speeds = []
# For each speed in the list
for speed in speeds:
# If the speed is in Kbps
if "kbps" in speed.lower():
# Fetch the raw speed integer and the unit name from the string
n_kbps, unit = speed.split()
# Convert the raw speed integer to Mbps
n_kbps /= 100
# Add the converted speed to the new_speeds array
new_speeds.append(f"{n_kbps} {unit}")
# If the speed is not in Kbps
else:
# Simply add the existing speed to the new_speeds array
new_speeds.append(speed)
# Set the original speeds array to the resulting array
speeds = new_speeds