I’m having trouble getting my desired output. I’m not sure how to go about the issue because every time I run the code I don’t get any output. So say I have a text file and in that text file it has
“firstName, 3010321, lastName, $432”
What I’m trying to do is essentially write a new file that puts the lastName after the firstName AND increase the bonus($432) by 10%.
Here is my code:
fullNames = []
numberID = []
Bonus = []
with open(“data.txt”) as file:
lines = file.readlines()
for name in lines:
firstName, numID, lastName, bonusAmount = name.split(“,”)
fullNames.append(firstName)
numberID.append(numID)
lastName, bonusAmount = name.split(“,”)
fullNames.append(lastName)
Bonus.append(bonusAmount * 10)
If possible, could I essentially write a new file using components from the file I’m reading?
CodePudding user response:
Here's one way to do it. Note that I'm using a StringIO
which is a file-like object, instead of reading from a local file. Also note that I'm splitting on ,
since this is the actual separator in the file (as there is a space after each comma).
from io import StringIO
string_value = StringIO("""\
firstName, 3010321, lastName, $432
Johnny, 1234567, Doe, $21\
""")
fullNames = []
numberID = []
Bonus = []
new_lines = []
lines = string_value.readlines()
for name in lines:
firstName, numID, lastName, bonusAmount = name.split(", ")
# Multiply it by 110%, which represents a 10% increase
bonusAmount = float(bonusAmount.lstrip('$')) * 1.10
fullNames.append((firstName, lastName))
numberID.append(numID)
Bonus.append(bonusAmount)
line = f'{firstName}, {lastName}, {numID}, ${bonusAmount:.2f}'
new_lines.append(line)
with open('out_file.txt', 'w') as out_file:
out_file.write('\n'.join(new_lines))
Contents of out_file.txt
:
firstName, lastName, 3010321, $475.20
Johnny, Doe, 1234567, $23.10
CodePudding user response:
Yes, you should create a new temporary file with the new data and rename when you are done. If something goes wrong before the rename, you haven't lost the data. Since the rows don't depend on each other, you can process them one at a time. No need to keep a list.
import os
filename = "data.txt"
with open(filename) as infile, open(filename ".tmp", "w") as outfile:
for line in infile:
firstName, numID, lastName, bonusAmount = (val.strip() for val in line.split(","))
newBonus = float(bonusAmount[1:]) * 1.1
outfile.write(f"{lastName}, {numID}, {firstName}, ${newBonus:.2f}\n")
os.rename(filename ".tmp", filename)